refactor: basically everything, move to src dir, move to sern build, publisher, v4, fix commands

This commit is contained in:
2024-09-20 19:32:03 +02:00
parent 8aeebb1164
commit 8ac9c16945
102 changed files with 2063 additions and 897 deletions

124
.sern/ambient.d.ts vendored Normal file
View File

@@ -0,0 +1,124 @@
declare var __DEV__: boolean
declare var __PROD__: boolean
declare var __VERSION__: string
declare namespace NodeJS {
interface ProcessEnv {
SHELL:string
SESSION_MANAGER:string
COLORTERM:string
XDG_CONFIG_DIRS:string
XDG_SESSION_PATH:string
COREPACK_ENABLE_DOWNLOAD_PROMPT:string
NVM_INC:string
XDG_MENU_PREFIX:string
TERM_PROGRAM_VERSION:string
ICEAUTHORITY:string
NODE_OPTIONS:string
LC_ADDRESS:string
LC_NAME:string
MEMORY_PRESSURE_WRITE:string
DESKTOP_SESSION:string
LC_MONETARY:string
GTK_RC_FILES:string
NO_AT_BRIDGE:string
EDITOR:string
XDG_SEAT:string
PWD:string
LOGNAME:string
XDG_SESSION_DESKTOP:string
XDG_SESSION_TYPE:string
SYSTEMD_EXEC_PID:string
_:string
XAUTHORITY:string
VSCODE_GIT_ASKPASS_NODE:string
MOTD_SHOWN:string
GTK2_RC_FILES:string
HOME:string
COREPACK_ROOT:string
LANG:string
LC_PAPER:string
XDG_CURRENT_DESKTOP:string
npm_package_version:string
MEMORY_PRESSURE_WATCH:string
STARSHIP_SHELL:string
WAYLAND_DISPLAY:string
GIT_ASKPASS:string
XDG_SEAT_PATH:string
INVOCATION_ID:string
MANAGERPID:string
INIT_CWD:string
CHROME_DESKTOP:string
STARSHIP_SESSION_KEY:string
KDE_SESSION_UID:string
NVM_DIR:string
VSCODE_GIT_ASKPASS_EXTRA_ARGS:string
XKB_DEFAULT_LAYOUT:string
XDG_ACTIVATION_TOKEN:string
XDG_SESSION_CLASS:string
LC_IDENTIFICATION:string
TERM:string
npm_package_name:string
PROJECT_CWD:string
USER:string
VSCODE_GIT_IPC_HANDLE:string
QT_WAYLAND_RECONNECT:string
KDE_SESSION_VERSION:string
PAM_KWALLET5_LOGIN:string
DISPLAY:string
npm_lifecycle_event:string
SHLVL:string
NVM_CD_FLAGS:string
LC_TELEPHONE:string
LC_MEASUREMENT:string
XDG_VTNR:string
XDG_SESSION_ID:string
npm_config_user_agent:string
npm_execpath:string
XDG_RUNTIME_DIR:string
DEBUGINFOD_URLS:string
npm_package_json:string
LC_TIME:string
BUN_INSTALL:string
BERRY_BIN_FOLDER:string
XKB_DEFAULT_VARIANT:string
VSCODE_GIT_ASKPASS_MAIN:string
QT_AUTO_SCREEN_SCALE_FACTOR:string
JOURNAL_STREAM:string
XDG_DATA_DIRS:string
KDE_FULL_SESSION:string
GDK_BACKEND:string
BROWSER:string
PATH:string
ORIGINAL_XDG_CURRENT_DESKTOP:string
DBUS_SESSION_BUS_ADDRESS:string
KDE_APPLICATIONS_AS_SCOPE:string
MAIL:string
NVM_BIN:string
npm_node_execpath:string
LC_NUMERIC:string
OLDPWD:string
TERM_PROGRAM:string
TOKEN:string
PREFIX:string
MONGODB:string
YOURLS_KEY:string
CATAPI:string
DOGAPI:string
TWITTER:string
MAKESWEET:string
GENIUS:string
SPOTIFY_CLIENT:string
SPOTIFY_SECRET:string
CF_AI_TOKEN:string
CF_AI_ACC:string
GUILDID:string
SUGGESTIONS_CHANNEL:string
MODLOGS_CHANNEL:string
JOINSANDLEAVES_CHANNEL:string
SOCIALS_CHANNEL:string
BIRTHDAYS_CHANNEL:string
MCFORM_CHANNEL:string
CHATGPT_CHANNEL:string
T_CHANNEL:string
}
}

File diff suppressed because it is too large Load Diff

17
.sern/tsconfig.json Normal file
View File

@@ -0,0 +1,17 @@
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "node16",
"strict": true,
"skipLibCheck": true,
"target": "esnext",
"rootDirs": [
"./generated",
"../src"
]
},
"include": [
"./ambient.d.ts",
"../src"
]
}

Binary file not shown.

View File

@@ -21,9 +21,8 @@ FROM node:lts-alpine AS final
WORKDIR /app WORKDIR /app
COPY --from=build /app/dist ./dist COPY --from=build /app/dist ./dist
COPY --from=build /app/schemas ./schemas COPY --from=build /app/src ./src
COPY --from=build /app/util ./util COPY --from=build /app/assets ./assets
COPY --from=build /app/images ./images
COPY --from=build /app/node_modules ./node_modules COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/package.json ./package.json COPY --from=build /app/package.json ./package.json
RUN apk add --no-cache ffmpeg msttcorefonts-installer fontconfig && \ RUN apk add --no-cache ffmpeg msttcorefonts-installer fontconfig && \

View File

@@ -1,15 +0,0 @@
import { commandModule, CommandType } from '@sern/handler';
import axios from 'axios';
export default commandModule({
type: CommandType.Button,
plugins: [],
execute: async (ctx) => {
await ctx.deferReply({ ephemeral: true })
const request = await axios.get('https://api.minetools.eu/query/minecraft.maraturing.com/25565').then(res => res.data)
await ctx.editReply({
content: ``
})
},
});

View File

@@ -1,19 +0,0 @@
import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins";
import { ApplicationCommandOptionType } from "discord.js";
/*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"
*/
export default commandModule({
name: 'askjavi',
type: CommandType.Slash,
plugins: [publish()],
description: 'DESACTIVADO: Pregunta a Javi LO QUE SEA!',
//alias : [],
execute: async (ctx, options) => {
await ctx.reply({content: `Este comando ha sido desactivado ya que era para un evento que ya ha ocurrido.\nGracias por haber participado!`, ephemeral: true})
},
});

View File

@@ -1,36 +0,0 @@
import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins";;
import { ApplicationCommandOptionType, EmbedBuilder, GuildMember, TextChannel } from 'discord.js'
export default commandModule({
name: 'ban',
type: CommandType.Slash,
plugins: [publish(), ownerOnly()],
description: 'ADMIN: Banea usuarios.',
options: [{
name: 'usuario',
description: 'Escribe un usuario.',
type: ApplicationCommandOptionType.User,
required: true
},
{
name: 'razon',
description: 'Escribe la razón.',
type: ApplicationCommandOptionType.String,
required: true
}],
//alias : [],
execute: async (ctx, options) => {
try {
const userToBan = options[1].getMember('usuario') as GuildMember
const reason = options[1].getString('razon') as string
userToBan.ban({reason: reason})
const sendToMods = ctx.client.guilds.cache.get(process.env.GUILDID!)!.channels.cache.get(process.env.MODLOGS_CHANNEL!) as TextChannel
await sendToMods.send({content: `Se ha baneado a ${userToBan}.\nBan efectuado por ${ctx.user} con razón "${reason}."`})
await ctx.reply({content: 'Baneado correctamente!', ephemeral: true})
} catch {
await ctx.reply({content: `ERROR: No puedo hacer este comando porque a lo mejor soy inferior que el rol de esa persona o estoy usándolo contra admins.`})
}
},
});

View File

@@ -1,42 +0,0 @@
import { commandModule, CommandType } from '@sern/handler'
import { publish } from "../../plugins/index.js";
import { ownerOnly } from "#plugins";
import { ApplicationCommandOptionType, TextChannel } from "discord.js";
/*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"
*/
export default commandModule({
name: 'eliminarmensaje',
type: CommandType.Slash,
plugins: [publish(), ownerOnly()],
description: 'ADMIN: Elimina comandos por su ID.',
//alias : [],
options: [
{
name: 'canal',
type: ApplicationCommandOptionType.Channel,
description: 'El canal de texto.',
required: true
},
{
name: 'id',
type: ApplicationCommandOptionType.String,
description: 'El ID del mensaje.',
required: true
}
],
execute: async (ctx, options) => {
try {
const idMensaje = options[1].getString('id', true);
const guildId = ctx.guild!.id
const guild = await ctx.client.guilds.fetch(guildId);
const channel = await guild.channels.fetch(ctx.channel!.id);
(await (channel as TextChannel).messages.fetch(idMensaje)).delete();
await ctx.reply({content: 'Mensaje eliminado correctamente.', ephemeral: true});
} catch {
await ctx.reply({content: `ERROR: No se ha podido eliminar el mensaje, asegúrate que estás usando el ID y el canal correcto.`})
}
},
});

View File

@@ -1,38 +0,0 @@
import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins";;
import { ApplicationCommandOptionType, EmbedBuilder, GuildMember, TextChannel } from 'discord.js'
export default commandModule({
name: 'kick',
type: CommandType.Slash,
plugins: [publish(), ownerOnly()],
description: 'ADMIN: Expulsa usuarios.',
options: [
{
name: 'usuario',
description: 'Escribe un usuario.',
type: ApplicationCommandOptionType.User,
required: true
},
{
name: 'razon',
description: 'Escribe la razón.',
type: ApplicationCommandOptionType.String,
required: true
}
],
//alias : [],
execute: async (ctx, options) => {
try {
const userToKick = options[1].getMember('usuario');
const reason = options[1].getString('razon') as string;
(userToKick as GuildMember).kick(reason)
const sendToMods = ctx.client.guilds.cache.get(process.env.GUILDID!)!.channels.cache.get(process.env.MODLOGS_CHANNEL!) as TextChannel
await sendToMods!.send({content: `Se ha expulsado a ${userToKick}.\nKick efectuado por ${ctx.user} con razón "${reason}."`})
await ctx.reply({content: 'Expulsado correctamente!'})
} catch {
await ctx.reply({content: `ERROR: No puedo hacer este comando porque a lo mejor soy inferior que el rol de esa persona o estoy usándolo contra admins.`})
}
},
});

View File

@@ -1,50 +0,0 @@
import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins";
import { ApplicationCommandOptionType, GuildMember, TextChannel } from "discord.js";
/*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"
*/
export default commandModule({
name: 'timeout',
type: CommandType.Slash,
plugins: [publish(), ownerOnly()],
description: 'ADMIN: Silencia a usuarios.',
options: [
{
name: "usuario",
description: "Escribe el usuario que silenciar.",
type: ApplicationCommandOptionType.User,
required: true
},
{
name: "razon",
description: "Escribe el razon que vas a silenciar.",
type: ApplicationCommandOptionType.String,
required: true
},
{
name: "minutos",
description: "Escribe los minutos que estará silenciado.",
type: ApplicationCommandOptionType.Number,
min_value: 0,
required: true
}
],
//alias : [],
execute: async (ctx, options) => {
try {
const usuario = options[1].getMember('usuario') as GuildMember
const minutos = options[1].getNumber('minutos') as number
const razon = options[1].getString('razon', true);
const minutosToMilisegundos = minutos * 60 * 1000
usuario.timeout(minutosToMilisegundos, razon).then(() => {ctx.reply({content: `Se ha silenciado a ${usuario} correctamente.`, ephemeral: true})})
const sendToMods = ctx.client.guilds.cache.get(process.env.GUILDID!)!.channels.cache.get(process.env.MODLOGS_CHANNEL!) as TextChannel
await sendToMods.send({content: `Se ha silenciado a ${usuario}.\nSlencio efectuado por ${ctx.user} con ${minutos} minutos de duración.\nRazón: ${razon}`})
} catch {
await ctx.reply({content: `ERROR: No puedo hacer este comando porque a lo mejor soy inferior que el rol de esa persona o estoy usándolo contra admins.`})
}
},
});

View File

@@ -1,212 +0,0 @@
import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins";;
import { ActionRowBuilder, ApplicationCommandOptionType, ButtonBuilder, ButtonInteraction, ButtonStyle, ComponentType, EmbedBuilder, GuildMember } from "discord.js";
import db from '../../schemas/warn.js';
export default commandModule({
name: 'warn',
type: CommandType.Slash,
plugins: [publish(), ownerOnly()],
description: 'ADMIN: Avisa a usuarios.',
//alias : [],
options: [
{
name: 'leve',
description: 'Aviso leve.',
type: ApplicationCommandOptionType.Subcommand,
options: [
{
name: 'usuario',
description: 'el usuario al que avisar.',
type: ApplicationCommandOptionType.User,
required: true
},
{
name: 'razon',
description: 'la razón aviso.',
type: ApplicationCommandOptionType.String,
required: true
}
]
},
{
name: 'grave',
description: 'Aviso grave.',
type: ApplicationCommandOptionType.Subcommand,
options: [
{
name: 'usuario',
description: 'el usuario al que avisar.',
type: ApplicationCommandOptionType.User,
required: true
},
{
name: 'razon',
description: 'la razón del aviso.',
type: ApplicationCommandOptionType.String,
required: true
}
]
},
{
name: 'clear',
description: 'Elimina los avisos de una persona.',
type: ApplicationCommandOptionType.Subcommand,
options: [
{
name: 'usuario',
description: 'el usuario al que quitar el aviso.',
type: ApplicationCommandOptionType.User,
required: true
}
]
}
],
execute: async (ctx, options) => {
const subcommand = options[1].getSubcommand()
const user = (options[1].getMember('usuario') as GuildMember).id
const usermember = options[1].getMember('usuario') as GuildMember
const reason = options[1].getString('razon', true) as string
const times = await db.findOne({id: `${user}`}) as any
const buttons = new ActionRowBuilder<ButtonBuilder>()
.addComponents(
new ButtonBuilder()
.setCustomId('1hour')
.setLabel('1 hora')
.setStyle(ButtonStyle.Danger),
new ButtonBuilder()
.setCustomId('30mins')
.setLabel('30 minutos')
.setStyle(ButtonStyle.Danger),
new ButtonBuilder()
.setCustomId('15mins')
.setLabel('15 minutos')
.setStyle(ButtonStyle.Danger),
new ButtonBuilder()
.setCustomId('pardon')
.setLabel('Perdonar')
.setStyle(ButtonStyle.Primary)
);
const dmEmbed = new EmbedBuilder()
.setAuthor({name: `${ctx.user.username}`, iconURL: `${ctx.user.displayAvatarURL()}`})
.setColor('Red')
.setTitle('Tienes un aviso.')
.setDescription(`Has sido avisado en el servidor de Discord.\nRazón: ${reason}.`)
const dmEmbedTimeout = new EmbedBuilder()
.setAuthor({name: `${ctx.user.username}`, iconURL: `${ctx.user.displayAvatarURL()}`})
.setColor('Red')
.setTitle('Acabas de ser muteado del servidor.')
.setDescription(`Ve al servidor de Discord para ver el tiempo que estarás bloqueado.\nRazón: ${reason}.\n**Puede durar hasta una hora.**`)
switch (subcommand) {
case "leve": {
return db.exists({id: `${user}`}, async function (err, doc) {
if (err) {
console.log(err)
} else {
if (doc === null) {
const warn = new db({id: `${user}`, times: 1})
warn.save()
ctx.reply({content: `Se ha avisado a ${usermember} correctamente y añadido a la base de datos.`, ephemeral: true})
ctx.client.users.fetch(user).then((user) => {
user.send({embeds: [dmEmbed]})
}).catch(() => console.log(`couldn't send a DM to user ID ${user}.`));
} else {
if (times.times > 2) {
const msg = await ctx.reply({content: `El usuario ha excedido 3 avisos, ¿qué hacer?`, ephemeral: true, components: [buttons]})
const collector = msg.createMessageComponentCollector({ time: 15000, max: 1, componentType: ComponentType.Button });
collector.on('collect', async (i) => {
await i.deferReply({ephemeral: true})
if (i.customId === '1hour') {
await i.editReply({content: `Se ha silenciado a ${usermember} durante 1 hora correctamente. ;-;`})
usermember.timeout(60 * 60 * 1000, reason)
times.times = 0
times.save()
} else if (i.customId === '30mins') {
await i.editReply({content: `Se ha silenciado a ${usermember} durante 30 minutos correctamente. ;-;`})
usermember.timeout(30 * 60 * 1000, reason)
times.times = 0
times.save()
} else if (i.customId === '15mins') {
await i.editReply({content: `Se ha silenciado a ${usermember} durante 15 minutos correctamente. ;-;`})
usermember.timeout(15 * 60 * 1000, reason)
times.times = 0
times.save()
} else if (i.customId === 'pardon') {
await i.editReply({content: `Se ha perdonado a ${usermember} correctamente.\nSeguro que la persona te lo agradecerá! :'D`})
times.times = 0
times.save()
}
ctx.client.users.fetch(user).then((user) => {
user.send({embeds: [dmEmbedTimeout]})
}).catch(() => console.log(`couldn't send a DM to user ID ${user}.`));
});
} else {
ctx.reply({content: `se ha añadido un aviso con el motivo ${reason}.\navisos que tiene ahora: ${times.times + 1}`, ephemeral: true})
times.times = times.times + 1
times.save()
ctx.client.users.fetch(user).then((user) => {
user.send({embeds: [dmEmbed]});
}).catch(() => console.log(`couldn't send a DM to user ID ${user}.`))
}
}
}
});
}
case "grave": {
return db.exists({id: `${user}`}, async function (err, doc) {
if (err) {
console.log(err)
} else {
if (doc === null) {
const warn = new db({id: `${user}`, times: 2})
warn.save()
ctx.reply({content: `Se ha avisado a ${usermember} correctamente y añadido a la base de datos.`, ephemeral: true})
ctx.client.users.fetch(user).then((user) => {
user.send({embeds: [dmEmbed]});
}).catch(() => console.log(`couldn't send a DM to user ID ${user}.`))
} else {
if (times.times >= 4) {
const msg = await ctx.reply({content: `El usuario ha excedido 3 avisos, ¿qué hacer?`, ephemeral: true, components: [buttons]})
const collector = msg.createMessageComponentCollector({ time: 1000, max: 1, componentType: ComponentType.Button });
collector.on('collect', async (i: any) => {
if (i.customId === '1hour') {
await i.channel!.send({content: `Se ha silenciado a ${usermember} durante 1 hora correctamente. ;-;`})
usermember.timeout(60 * 60 * 1000, reason)
times.times = 0
times.save()
} else if (i.customId === '30mins') {
await i.channel!.send({content: `Se ha silenciado a ${usermember} durante 30 minutos correctamente. ;-;`})
usermember.timeout(30 * 60 * 1000, reason)
times.times = 0
times.save()
} else if (i.customId === '15mins') {
await i.channel!.send({content: `Se ha silenciado a ${usermember} durante 15 minutos correctamente. ;-;`})
usermember.timeout(15 * 60 * 1000, reason)
times.times = 0
times.save()
} else if (i.customId === 'pardon') {
await i.channel!.send({content: `Se ha perdonado a ${usermember} correctamente.\nSeguro que la persona te lo agradecerá! :'D`})
times.times = 0
times.save()
}
ctx.client.users.fetch(user).then((user) => {
user.send({embeds: [dmEmbedTimeout]})
}).catch(() => console.log(`couldn't send a DM to user ID ${user}.`));
});
} else {
ctx.reply({content: `se ha añadido un aviso con el motivo ${reason}.\navisos que tiene ahora: ${times.times + 2}`, ephemeral: true})
times.times = times.times + 2
times.save()
ctx.client.users.fetch(user).then((user) => {
user.send({embeds: [dmEmbed]});
}).catch(() => console.log(`couldn't send a DM to user ID ${user}.`))
}
}
}
});
}
}
}
})

View File

@@ -1,10 +0,0 @@
#!/bin/bash
git pull
docker build . -t srizan10/vinci
docker stop vinci
docker rm vinci
docker run -d -t --name vinci -p 7272:7272 --restart unless-stopped srizan10/vinci

View File

@@ -5,7 +5,7 @@
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
"dev": "tsc-watch -p \"./tsconfig.json\" --onSuccess \"node ./dist/index.js --dev\"", "dev": "sern build && node ./dist/index.js --dev",
"prod": "tsc-watch -p \"./tsconfig.json\" --onSuccess \"node ./dist/index.js\"", "prod": "tsc-watch -p \"./tsconfig.json\" --onSuccess \"node ./dist/index.js\"",
"compile": "tsc --build", "compile": "tsc --build",
"build": "tsc --build", "build": "tsc --build",
@@ -34,23 +34,24 @@
"homepage": "https://github.com/SrIzan10/vinci#readme", "homepage": "https://github.com/SrIzan10/vinci#readme",
"dependencies": { "dependencies": {
"@ai-zen/node-fetch-event-source": "^2.1.4", "@ai-zen/node-fetch-event-source": "^2.1.4",
"@consumet/extensions": "1.3.5", "@consumet/extensions": "^1.7.0",
"@discordjs/opus": "^0.9.0", "@discordjs/opus": "^0.9.0",
"@discordjs/voice": "^0.15.0", "@discordjs/voice": "^0.15.0",
"@microsoft/fetch-event-source": "^2.0.1", "@microsoft/fetch-event-source": "^2.0.1",
"@napi-rs/canvas": "^0.1.52", "@napi-rs/canvas": "^0.1.52",
"@sern/handler": "^3.3.4", "@sern/handler": "^4.0.2",
"@sern/publisher": "^1.1.2",
"axios": "^1.6.8", "axios": "^1.6.8",
"dayjs": "^1.11.6", "dayjs": "^1.11.6",
"discord-tictactoe": "^4.0.0", "discord-tictactoe": "^4.0.0",
"discord.js": "^14.14.1", "discord.js": "^14.16.2",
"dotenv": "^16.0.1", "dotenv": "^16.0.1",
"execa": "^6.1.0", "execa": "^6.1.0",
"express": "^4.18.1", "express": "^4.18.1",
"extended-eventsource": "^1.4.6", "extended-eventsource": "^1.4.6",
"form-data": "^4.0.0", "form-data": "^4.0.0",
"genius-lyrics": "^4.4.3", "genius-lyrics": "^4.4.3",
"googlethis": "^1.7.1", "googlethis": "^1.8.0",
"got": "^12.5.3", "got": "^12.5.3",
"libsodium-wrappers": "^0.7.10", "libsodium-wrappers": "^0.7.10",
"mongoose": "^6.11.3", "mongoose": "^6.11.3",
@@ -68,7 +69,7 @@
"@types/node": "^20.12.7", "@types/node": "^20.12.7",
"ts-node": "10.9.1", "ts-node": "10.9.1",
"tsc-watch": "^5.0.3", "tsc-watch": "^5.0.3",
"typescript": "^5.4.5" "typescript": "^5.6.2"
}, },
"packageManager": "yarn@4.1.1" "packageManager": "yarn@4.1.1"
} }

View File

@@ -1,9 +0,0 @@
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
number: {type: Number, required: true}
})
const db = new mongoose.Model('counting', schema)
module.exports = db;

View File

@@ -1,7 +1,7 @@
{ {
"language": "typescript", "language": "typescript",
"paths": { "paths": {
"base": ".", "base": "src",
"commands": "commands" "commands": "commands"
} }
} }

View File

@@ -1,16 +1,10 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins";
import { ApplicationCommandOptionType } from "discord.js"; import { ApplicationCommandOptionType } from "discord.js";
/*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"
*/
export default commandModule({ export default commandModule({
name: '8ball', name: '8ball',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Preguntale a la 8-ball cosas.', description: 'Preguntale a la 8-ball cosas.',
//alias : [], //alias : [],
options: [{ options: [{
@@ -19,8 +13,8 @@ export default commandModule({
type: ApplicationCommandOptionType.String, type: ApplicationCommandOptionType.String,
required: true required: true
}], }],
execute: async (ctx, options) => { execute: async (ctx) => {
// yes, the question argument is never used. There is no reason to use it in the code. // yes, the question argument is never used. There is no reason to use it.
var eightballwords = [ var eightballwords = [
'Probablemente', 'Probablemente',
'Sí', 'Sí',

View File

@@ -2,10 +2,8 @@ import { commandModule, CommandType } from '@sern/handler';
import { import {
ApplicationCommandOptionType, ApplicationCommandOptionType,
AttachmentBuilder, AttachmentBuilder,
AutocompleteInteraction,
EmbedBuilder, EmbedBuilder,
} from 'discord.js'; } from 'discord.js';
import { publish } from '#plugins';
const choices = [ const choices = [
'XaviXE', 'XaviXE',
'Paula', 'Paula',
@@ -28,9 +26,8 @@ const choices = [
export default commandModule({ export default commandModule({
name: 'a', name: 'a',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'A', description: 'A',
//alias : [],
options: [ options: [
{ {
name: 'usuario', name: 'usuario',
@@ -39,7 +36,7 @@ export default commandModule({
autocomplete: true, autocomplete: true,
command: { command: {
onEvent: [], onEvent: [],
async execute(ctx: AutocompleteInteraction) { async execute(ctx) {
const focusedValue = ctx.options.getFocused(); const focusedValue = ctx.options.getFocused();
const filtered = choices.filter((choice) => const filtered = choices.filter((choice) =>
choice.startsWith(focusedValue) choice.startsWith(focusedValue)
@@ -48,10 +45,10 @@ export default commandModule({
filtered.map((choice) => ({ name: choice, value: choice })) filtered.map((choice) => ({ name: choice, value: choice }))
); );
}, },
}, }
}, },
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
const option = ctx.interaction.options.getString('usuario'); const option = ctx.interaction.options.getString('usuario');
if (!option) { if (!option) {
const imagesArray = [ const imagesArray = [
@@ -77,9 +74,9 @@ export default commandModule({
await ctx.reply({ content: 'A', files: [images] }); await ctx.reply({ content: 'A', files: [images] });
} else { } else {
if (choices.indexOf(options[1].getString('usuario', true)) > -1) { if (choices.indexOf(option) > -1) {
const attachmentbuilder = new AttachmentBuilder( const attachmentbuilder = new AttachmentBuilder(
`./images/a/${options[1].getString('usuario', true)}.png` `./images/a/${option}.png`
); );
await ctx.reply({ content: 'A', files: [attachmentbuilder] }); await ctx.reply({ content: 'A', files: [attachmentbuilder] });
} else { } else {

View File

@@ -1,16 +1,11 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import axios from "axios"; import axios from "axios";
import { ActionRowBuilder, ApplicationCommandOptionType, ButtonBuilder, ButtonStyle, ComponentType, EmbedBuilder } from "discord.js"; import { ActionRowBuilder, ApplicationCommandOptionType, ButtonBuilder, ButtonStyle, ComponentType, EmbedBuilder } from "discord.js";
import { publish } from "#plugins";
/*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"
*/
export default commandModule({ export default commandModule({
name: 'animal', name: 'animal',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Enseña un animal', description: 'Enseña un animal',
//alias : [], //alias : [],
options: [ options: [
@@ -40,8 +35,8 @@ export default commandModule({
type: ApplicationCommandOptionType.Subcommand type: ApplicationCommandOptionType.Subcommand
} }
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
switch (options[1].getSubcommand()) { switch (ctx.options.getSubcommand()) {
case 'gato': { case 'gato': {
const request = await axios.get(`https://api.thecatapi.com/v1/images/search?api_key=${process.env.CATAPI}`).then(res => res.data) const request = await axios.get(`https://api.thecatapi.com/v1/images/search?api_key=${process.env.CATAPI}`).then(res => res.data)
const embed = new EmbedBuilder() const embed = new EmbedBuilder()

View File

@@ -1,14 +1,9 @@
import { commandModule, CommandType } from '@sern/handler'; import { commandModule, CommandType } from '@sern/handler';
import { publish } from '#plugins';
/*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"
*/
export default commandModule({ export default commandModule({
name: 'cursivify', name: 'cursivify',
type: CommandType.CtxMsg, type: CommandType.CtxMsg,
plugins: [publish()], plugins: [],
execute: async (ctx) => { execute: async (ctx) => {
await ctx.deferReply() await ctx.deferReply()
const trimmedstring = ctx.targetMessage.content.replaceAll('*', ''); const trimmedstring = ctx.targetMessage.content.replaceAll('*', '');

View File

@@ -10,13 +10,13 @@ import {
EmbedBuilder, EmbedBuilder,
} from 'discord.js'; } from 'discord.js';
/* /*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins" import { ownerOnly } from "#plugins"
*/ */
export default commandModule({ export default commandModule({
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'busca cosas en gogoanime', description: 'busca cosas en gogoanime',
//alias : [], //alias : [],
options: [ options: [
@@ -91,10 +91,10 @@ export default commandModule({
execute: async (ctx, options) => { execute: async (ctx, options) => {
const gogoanime = new ANIME.Gogoanime(); const gogoanime = new ANIME.Gogoanime();
const doubleslashregex = new RegExp('(?<!:)\/\/+') const doubleslashregex = new RegExp('(?<!:)\/\/+')
switch (options[1].getSubcommand()) { switch (ctx.options.getSubcommand()) {
case 'buscar': { case 'buscar': {
await ctx.interaction.deferReply() await ctx.interaction.deferReply()
const option = options[1].getString('palabra-clave', true); const option = ctx.options.getString('palabra-clave', true);
const search = await gogoanime.search(option); const search = await gogoanime.search(option);
const editedarray = await Promise.all( const editedarray = await Promise.all(
search.results search.results
@@ -132,7 +132,7 @@ export default commandModule({
}) })
} break; } break;
case 'capitulo': { case 'capitulo': {
const selepisode = options[1].getString('id-capitulo', true) const selepisode = ctx.options.getString('id-capitulo', true)
try { try {
const search = await gogoanime.fetchEpisodeServers(selepisode) const search = await gogoanime.fetchEpisodeServers(selepisode)
const arrayed = await Promise.all(search.map((server) => `[${server.name}](<${server.url!.replace(doubleslashregex, '/')}>)`)) const arrayed = await Promise.all(search.map((server) => `[${server.name}](<${server.url!.replace(doubleslashregex, '/')}>)`))
@@ -143,7 +143,7 @@ export default commandModule({
} break; } break;
case 'info': { case 'info': {
try { try {
const option = options[1].getString('id', true) const option = ctx.options.getString('id', true)
const info = await gogoanime.fetchAnimeInfo(option) const info = await gogoanime.fetchAnimeInfo(option)
const embed = new EmbedBuilder() const embed = new EmbedBuilder()
.setColor('Random') .setColor('Random')

View File

@@ -1,13 +1,13 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import axios from "axios"; import axios from "axios";
import { publish } from "#plugins";
export default commandModule({ export default commandModule({
name: 'chiste', name: 'chiste',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Enseña un chiste en inglés.', description: 'Enseña un chiste en inglés.',
execute: async (ctx, args) => { execute: async (ctx) => {
const jokeJSON = await axios( const jokeJSON = await axios(
'https://v2.jokeapi.dev/joke/Programming,Miscellaneous,Spooky,Christmas?blacklistFlags=nsfw,religious,racist,sexist,explicit' 'https://v2.jokeapi.dev/joke/Programming,Miscellaneous,Spooky,Christmas?blacklistFlags=nsfw,religious,racist,sexist,explicit'
).then((res) => res.data); ).then((res) => res.data);

View File

@@ -11,13 +11,13 @@ import {
import axios from 'axios'; import axios from 'axios';
import https from 'node:https' import https from 'node:https'
/* /*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins" import { ownerOnly } from "#plugins"
*/ */
export default commandModule({ export default commandModule({
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
//alias : [], //alias : [],
description: 'no one will read this (i hope)', description: 'no one will read this (i hope)',
options: [ options: [
@@ -40,15 +40,15 @@ export default commandModule({
], ],
}, },
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
await ctx.interaction.deferReply(); await ctx.interaction.deferReply();
switch (options[1].getSubcommand()) { switch (ctx.options.getSubcommand()) {
case 'heartlocket': case 'heartlocket':
{ {
try { try {
// get all options // get all options
const text = options[1].getString('texto'); const text = ctx.options.getString('texto', true);
const image = options[1].getAttachment('imagen', true); const image = ctx.options.getAttachment('imagen', true);
// check file extension of attachment // check file extension of attachment
if ( if (
@@ -110,6 +110,7 @@ export default commandModule({
Authorization: process.env.MAKESWEET!, Authorization: process.env.MAKESWEET!,
}, },
responseType: 'arraybuffer', responseType: 'arraybuffer',
httpsAgent: new https.Agent({ rejectUnauthorized: false })
} }
) )
.then((res) => res.data); .then((res) => res.data);
@@ -120,6 +121,7 @@ export default commandModule({
Authorization: process.env.MAKESWEET!, Authorization: process.env.MAKESWEET!,
}, },
responseType: 'arraybuffer', responseType: 'arraybuffer',
httpsAgent: new https.Agent({ rejectUnauthorized: false })
}) })
.then((res) => res.data); .then((res) => res.data);
} }

View File

@@ -1,16 +1,16 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"; import { ownerOnly } from "#plugins";
import Canvas from '@napi-rs/canvas'; import Canvas from '@napi-rs/canvas';
import { ApplicationCommandOptionType, AttachmentBuilder } from 'discord.js'; import { ApplicationCommandOptionType, AttachmentBuilder } from 'discord.js';
/* /*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins" import { ownerOnly } from "#plugins"
*/ */
export default commandModule({ export default commandModule({
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
// , '928018226330337280' // , '928018226330337280'
description: 'Añade a una imagen de megamind "No ...?"', description: 'Añade a una imagen de megamind "No ...?"',
//alias : [], //alias : [],
@@ -22,8 +22,8 @@ export default commandModule({
required: true required: true
} }
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
const option = options[1].getString('texto', true) const option = ctx.options.getString('texto', true)
await ctx.reply({content: 'Cargando...'}) await ctx.reply({content: 'Cargando...'})

View File

@@ -1,12 +1,12 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { ActionRowBuilder, ApplicationCommandOptionType, ButtonBuilder, ButtonStyle, ComponentType, EmbedBuilder, GuildMember } from "discord.js"; import { ActionRowBuilder, ApplicationCommandOptionType, ButtonBuilder, ButtonStyle, ComponentType, EmbedBuilder, GuildMember } from "discord.js";
import { publish } from "#plugins";
import rockpaperscissors from "rockpaperscissors-checker"; import rockpaperscissors from "rockpaperscissors-checker";
export default commandModule({ export default commandModule({
name: 'rps', name: 'rps',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Juega piedra papel tijeras con los panas', description: 'Juega piedra papel tijeras con los panas',
//alias : [], //alias : [],
options: [ options: [
@@ -17,10 +17,10 @@ export default commandModule({
required: true required: true
} }
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
// also the code is mine, I didn't steal from anyone // also the code is mine, I didn't steal from anyone
let player1, player2, winner, bothResponded let player1: number, player2: number, winner, bothResponded: boolean
const option = options[1].getMember('usuario') as GuildMember const option = ctx.options.getMember('usuario') as unknown as GuildMember
if (ctx.user.id === option.id) { if (ctx.user.id === option.id) {
return await ctx.reply({content: `no puedes jugar contigo mismo 💀`, ephemeral: true}) return await ctx.reply({content: `no puedes jugar contigo mismo 💀`, ephemeral: true})
} else if (option.user.bot) { } else if (option.user.bot) {

View File

@@ -1,14 +1,13 @@
import TicTacToe from 'discord-tictactoe'; import TicTacToe from 'discord-tictactoe';
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"; import { ApplicationCommandOptionType } from "discord.js";
import { ApplicationCommandOptionType, ChatInputCommandInteraction, CommandInteraction, Interaction } from "discord.js";
const game = new TicTacToe({language: 'en'}) const game = new TicTacToe({language: 'en'})
export default commandModule({ export default commandModule({
name: 'tictactoe', name: 'tictactoe',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'tres en raya', description: 'tres en raya',
//alias : [], //alias : [],
options: [ options: [

View File

@@ -8,7 +8,7 @@ import { execa } from 'execa';
export default commandModule({ export default commandModule({
type: CommandType.CtxMsg, type: CommandType.CtxMsg,
plugins: [publish()], plugins: [],
execute: async (ctx) => { execute: async (ctx) => {
await ctx.deferReply({ fetchReply: true }) await ctx.deferReply({ fetchReply: true })
@@ -22,11 +22,11 @@ export default commandModule({
const randomnumber = random(5) const randomnumber = random(5)
const randomnumber_wav = `bonzi-wav-${randomnumber}.wav` const randomnumber_wav = `bonzi-wav-${randomnumber}.wav`
const randomnumber_mp3 = `bonzi-mp3-${randomnumber}.mp3` const randomnumber_mp3 = `bonzi-mp3-${randomnumber}.mp3`
fs.writeFileSync(`./util/bonzi_temp/${randomnumber_wav}`, new Uint8Array(request)) fs.writeFileSync(`./src/util/bonzi_temp/${randomnumber_wav}`, new Uint8Array(request))
const command = execa('ffmpeg', [ const command = execa('ffmpeg', [
'-i', `./util/bonzi_temp/${randomnumber_wav}`, '-i', `./src/util/bonzi_temp/${randomnumber_wav}`,
'-vn', '-vn',
`./util/bonzi_temp/${randomnumber_mp3}` `./src/util/bonzi_temp/${randomnumber_mp3}`
], { shell: true }) ], { shell: true })
await new Promise((resolve) => { await new Promise((resolve) => {
command.on('close', resolve) command.on('close', resolve)
@@ -34,12 +34,12 @@ export default commandModule({
const stream = new Readable(); const stream = new Readable();
stream._read = () => {}; stream._read = () => {};
stream.push(Buffer.from(new Uint8Array(fs.readFileSync(`./util/bonzi_temp/${randomnumber_mp3}`)))); stream.push(Buffer.from(new Uint8Array(fs.readFileSync(`./src/util/bonzi_temp/${randomnumber_mp3}`))));
stream.push(null) stream.push(null)
const attachment = new AttachmentBuilder(stream, { name: 'bonzied.mp3' }) const attachment = new AttachmentBuilder(stream, { name: 'bonzied.mp3' })
fs.unlinkSync(`./util/bonzi_temp/${randomnumber_mp3}`) fs.unlinkSync(`./src/util/bonzi_temp/${randomnumber_mp3}`)
fs.unlinkSync(`./util/bonzi_temp/${randomnumber_wav}`) fs.unlinkSync(`./src/util/bonzi_temp/${randomnumber_wav}`)
await ctx.editReply({ files: [attachment] }) await ctx.editReply({ files: [attachment] })
}, },

View File

@@ -5,7 +5,6 @@ import {
ButtonBuilder, ButtonBuilder,
ButtonStyle, ButtonStyle,
EmbedBuilder, EmbedBuilder,
TextChannel,
} from 'discord.js'; } from 'discord.js';
export default commandModule({ export default commandModule({
@@ -53,11 +52,14 @@ export default commandModule({
.setLabel('Añadido a la whitelist!') .setLabel('Añadido a la whitelist!')
.setStyle(ButtonStyle.Success) .setStyle(ButtonStyle.Success)
); );
( const guild = await modal.client.guilds.fetch(process.env.GUILDID!);
(await ( const channel = await guild.channels.fetch(process.env.MCFORM_CHANNEL!);
await modal.client.guilds.fetch(process.env.GUILDID!) if (channel && channel.isTextBased()) {
).channels.fetch(process.env.MCFORM_CHANNEL!)) as TextChannel await channel.send({
).send({ embeds: [embed], components: [button] }); embeds: [embed],
components: [button],
});
}
} catch { } catch {
await modal.reply({ await modal.reply({
content: content:

View File

@@ -15,7 +15,7 @@ export default commandModule({
// @ts-ignore // @ts-ignore
).options.map((o: { label: string; value: string }) => o.value); ).options.map((o: { label: string; value: string }) => o.value);
const member = interaction.member as GuildMember; const member = interaction.member! as unknown as GuildMember;
if (!member) return; if (!member) return;
let content = `Los roles han sido actualizados. Te he dado estos:\n${roles let content = `Los roles han sido actualizados. Te he dado estos:\n${roles

View File

@@ -1,7 +1,6 @@
import { commandModule, CommandType } from '@sern/handler'; import { commandModule, CommandType } from '@sern/handler';
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder } from 'discord.js'; import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder } from 'discord.js';
import { import {
TextChannel,
ThreadAutoArchiveDuration, ThreadAutoArchiveDuration,
} from 'discord.js'; } from 'discord.js';
@@ -52,10 +51,17 @@ export default commandModule({
.setStyle(ButtonStyle.Secondary), .setStyle(ButtonStyle.Secondary),
) )
const message1 = await (await modal.client.guilds.fetch(process.env.GUILDID!)) const guild = await modal.client.guilds.fetch(process.env.GUILDID!);
.channels.fetch(process.env.SUGGESTIONS_CHANNEL!) as TextChannel; const channel = await guild.channels.fetch(process.env.SUGGESTIONS_CHANNEL!);
const message2 = await message1.send({ embeds: [embed], components: [row, row2] }); if (!channel || !channel.isTextBased()) {
message2.startThread({ return await modal.reply({
content: 'ERROR: Canal de sugerencias no encontrado.',
ephemeral: true,
});
}
const msg = await channel.send({ embeds: [embed], components: [row, row2] });
msg.startThread({
name: `Sugerencia de ${modal.user.username}`, name: `Sugerencia de ${modal.user.username}`,
autoArchiveDuration: ThreadAutoArchiveDuration.ThreeDays, autoArchiveDuration: ThreadAutoArchiveDuration.ThreeDays,
reason: 'AUTOMATIZADO: Hilo para discutir sobre la sugerencia.', reason: 'AUTOMATIZADO: Hilo para discutir sobre la sugerencia.',

View File

@@ -1,11 +1,11 @@
import { commandModule, CommandType } from "@sern/handler"; import { commandModule, CommandType } from "@sern/handler";
import { ActionRowBuilder, ButtonBuilder, ButtonComponentData, ButtonInteraction, ButtonStyle, ComponentType } from "discord.js"; import { ActionRowBuilder, ButtonBuilder, ButtonComponent, ButtonComponentData, ButtonStyle } from "discord.js";
import db from "../../schemas/suggestions.js"; import db from "../../schemas/suggestions.js";
export default commandModule({ export default commandModule({
type: CommandType.Button, type: CommandType.Button,
async execute(interaction) { async execute(interaction) {
const convertToNumber = Number(interaction.component.label!) const convertToNumber = Number((interaction.component as ButtonComponent).label!)
const row2 = new ActionRowBuilder<ButtonBuilder>().setComponents( const row2 = new ActionRowBuilder<ButtonBuilder>().setComponents(
new ButtonBuilder(interaction.message!.components[1].components[0].data as ButtonComponentData), new ButtonBuilder(interaction.message!.components[1].components[0].data as ButtonComponentData),
new ButtonBuilder(interaction.message!.components[1].components[1].data as ButtonComponentData) new ButtonBuilder(interaction.message!.components[1].components[1].data as ButtonComponentData)

View File

@@ -1,5 +1,4 @@
import { commandModule, CommandType } from "@sern/handler"; import { commandModule, CommandType } from "@sern/handler";
import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, ButtonStyle, ComponentType } from "discord.js";
import db from "../../schemas/suggestions.js"; import db from "../../schemas/suggestions.js";
export default commandModule({ export default commandModule({

View File

@@ -1,11 +1,11 @@
import { commandModule, CommandType } from "@sern/handler"; import { commandModule, CommandType } from "@sern/handler";
import { ActionRowBuilder, ButtonBuilder, ButtonComponentData, ButtonInteraction, ButtonStyle, ComponentType } from "discord.js"; import { ActionRowBuilder, ButtonBuilder, ButtonComponent, ButtonComponentData, ButtonStyle } from "discord.js";
import db from "../../schemas/suggestions.js"; import db from "../../schemas/suggestions.js";
export default commandModule({ export default commandModule({
type: CommandType.Button, type: CommandType.Button,
async execute(interaction) { async execute(interaction) {
const convertToNumber = Number(interaction.component.label!) const convertToNumber = Number((interaction.component as ButtonComponent).label!)
const row2 = new ActionRowBuilder<ButtonBuilder>().setComponents( const row2 = new ActionRowBuilder<ButtonBuilder>().setComponents(
new ButtonBuilder(interaction.message!.components[1].components[0].data as ButtonComponentData), new ButtonBuilder(interaction.message!.components[1].components[0].data as ButtonComponentData),
new ButtonBuilder(interaction.message!.components[1].components[1].data as ButtonComponentData) new ButtonBuilder(interaction.message!.components[1].components[1].data as ButtonComponentData)

View File

@@ -1,16 +1,10 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins";
import { ApplicationCommandOptionType } from "discord.js"; import { ApplicationCommandOptionType } from "discord.js";
/*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"
*/
export default commandModule({ export default commandModule({
name: 'ip', name: 'ip',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
// //
description: 'La IP del servidor de Minecraft', description: 'La IP del servidor de Minecraft',
options: [ options: [
@@ -22,7 +16,7 @@ export default commandModule({
], ],
//alias : [], //alias : [],
execute: async (ctx, options) => { execute: async (ctx, options) => {
const usuario = options[1].getMember('usuario'); const usuario = ctx.options.getMember('usuario');
if (!usuario) { if (!usuario) {
await ctx.reply({content: "La IP del servidor de Minecraft es `minecraft.maraturing.com`,\nPide acceso con el comando </mcform:1000747672690499594>.", ephemeral: true}) await ctx.reply({content: "La IP del servidor de Minecraft es `minecraft.maraturing.com`,\nPide acceso con el comando </mcform:1000747672690499594>.", ephemeral: true})

View File

@@ -6,13 +6,11 @@ import {
TextInputStyle, TextInputStyle,
ModalActionRowComponentBuilder, ModalActionRowComponentBuilder,
} from 'discord.js'; } from 'discord.js';
import { publish } from '#plugins';
import { ownerOnly } from '#plugins';
export default commandModule({ export default commandModule({
name: 'mcform', name: 'mcform',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Envia el formulario para entrar al servidor.', description: 'Envia el formulario para entrar al servidor.',
//alias : [], //alias : [],
execute: async (ctx) => { execute: async (ctx) => {

View File

@@ -1,16 +1,10 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"
import db from '../../schemas/afk.js'; import db from '../../schemas/afk.js';
import { ApplicationCommandOptionType, EmbedBuilder } from 'discord.js'; import { ApplicationCommandOptionType, EmbedBuilder } from 'discord.js';
/*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"
*/
export default commandModule({ export default commandModule({
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'afk command', description: 'afk command',
//alias : [], //alias : [],
options: [ options: [
@@ -38,11 +32,11 @@ export default commandModule({
type: ApplicationCommandOptionType.Subcommand type: ApplicationCommandOptionType.Subcommand
} }
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
switch (options[1].getSubcommand()) { switch (ctx.options.getSubcommand()) {
case 'añadir': { case 'añadir': {
if (await db.exists({ id: ctx.user.id })) return ctx.reply({ content: 'Ya existes en la base de datos!', ephemeral: true }) if (await db.exists({ id: ctx.user.id })) return ctx.reply({ content: 'Ya existes en la base de datos!', ephemeral: true })
const reason = options[1].getString('motivo', true); const reason = ctx.options.getString('motivo');
await (new db({ id: ctx.user.id, reason: reason })).save() await (new db({ id: ctx.user.id, reason: reason })).save()
const embed = new EmbedBuilder() const embed = new EmbedBuilder()

View File

@@ -11,16 +11,15 @@ import {
ModalSubmitInteraction, ModalSubmitInteraction,
ApplicationCommandOptionType, ApplicationCommandOptionType,
} from 'discord.js'; } from 'discord.js';
import { publish } from '#plugins';
import { ownerOnly } from '#plugins';
import padyama from '../../schemas/padyama.js'; import padyama from '../../schemas/padyama.js';
import { random } from '../../util/randomstring.js'; import { random } from '../../util/randomstring.js';
import { disable } from '#plugins';
export default commandModule({ export default commandModule({
name: 'askjavi', name: 'askjavi',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [ plugins: [
// publish(), disable()
], ],
description: 'TEMP: Pregunta a Javi LO QUE SEA!', description: 'TEMP: Pregunta a Javi LO QUE SEA!',
//alias : [], //alias : [],
@@ -63,7 +62,7 @@ export default commandModule({
], ],
}, },
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
switch (ctx.interaction.options.getSubcommand()) { switch (ctx.interaction.options.getSubcommand()) {
case 'new': { case 'new': {
const modal = new ModalBuilder() const modal = new ModalBuilder()
@@ -110,7 +109,7 @@ export default commandModule({
time: 180000, time: 180000,
filter: (i) => i.user.id === ctx.user.id, filter: (i) => i.user.id === ctx.user.id,
}) })
.catch((error) => {})) as ModalSubmitInteraction; .catch((error) => {})) as unknown as ModalSubmitInteraction;
const db = new padyama({ const db = new padyama({
id: i.user.id, id: i.user.id,
user: i.user.username, user: i.user.username,
@@ -132,7 +131,7 @@ export default commandModule({
}); });
} }
case 'get': { case 'get': {
const option = options[1].getString('id'); const option = ctx.options.getString('id');
const db = await padyama.findOne({ suggestionid: option }); const db = await padyama.findOne({ suggestionid: option });
if (db?.suggestion !== undefined) if (db?.suggestion !== undefined)
return await ctx.reply({ return await ctx.reply({
@@ -160,7 +159,7 @@ export default commandModule({
content: `No puedes usar este comando.`, content: `No puedes usar este comando.`,
ephemeral: true, ephemeral: true,
}); });
const option = options[1].getString('id'); const option = ctx.options.getString('id');
const db = await padyama.findOne({ suggestionid: option }); const db = await padyama.findOne({ suggestionid: option });
if (db?.user !== undefined) { if (db?.user !== undefined) {
try { try {

View File

@@ -1,16 +1,14 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { Context, SlashOptions } from "@sern/handler";
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder } from "discord.js"; import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder } from "discord.js";
import { publish } from "#plugins";
export default commandModule({ export default commandModule({
name: 'creditos', name: 'creditos',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Créditos del bot (en inglés)', description: 'Créditos del bot (en inglés)',
//alias : [], //alias : [],
options: [], options: [],
execute: async (ctx, options) => { execute: async (ctx) => {
const baseEmbed = new EmbedBuilder() const baseEmbed = new EmbedBuilder()
.setColor('Blurple') .setColor('Blurple')
.setTitle(`Without these people, the bot wouldn't exist!`) .setTitle(`Without these people, the bot wouldn't exist!`)

View File

@@ -1,18 +1,13 @@
import { commandModule, CommandType } from "@sern/handler"; import { commandModule, CommandType } from "@sern/handler";
import { publish } from "#plugins";
import { ApplicationCommandOptionType } from "discord.js"; import { ApplicationCommandOptionType } from "discord.js";
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import birthdays from "../../schemas/birthdays.js"; import birthdays from "../../schemas/birthdays.js";
import { acceptingBirthday } from "#plugins"; import { acceptingBirthday } from "#plugins";
/*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"
*/
export default commandModule({ export default commandModule({
name: "cumple", name: "cumple",
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish(), acceptingBirthday()], plugins: [acceptingBirthday()],
description: "Pon tu cumpleaños en la base de datos para ser felicitado!", description: "Pon tu cumpleaños en la base de datos para ser felicitado!",
//alias : [], //alias : [],
options: [ options: [
@@ -43,7 +38,7 @@ export default commandModule({
}, },
}, },
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
const option = ctx.interaction.options.getString("fecha") const option = ctx.interaction.options.getString("fecha")
const array = JSON.parse( const array = JSON.parse(
String(readFileSync("./util/daysinyear.txt")) String(readFileSync("./util/daysinyear.txt"))

View File

@@ -1,12 +1,10 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { ApplicationCommandOptionType, ColorResolvable, EmbedBuilder } from 'discord.js'; import { ApplicationCommandOptionType, ColorResolvable, EmbedBuilder } from 'discord.js';
import { publish } from "#plugins"; import mctags from '../../../assets/mcTags.json' with { type: "json" };
import fs from 'node:fs';
import mctags from '../../util/tags/minecraft.json' assert { type: 'json' }
export default commandModule({ export default commandModule({
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Preguntas normalmente preguntadas :pepega:', description: 'Preguntas normalmente preguntadas :pepega:',
//alias : [], //alias : [],
options: [ options: [
@@ -40,11 +38,11 @@ export default commandModule({
] ]
} }
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
switch (options[1].getSubcommand()) { switch (ctx.options.getSubcommand()) {
case 'minecraft': { case 'minecraft': {
const option = options[1].getString('pregunta', true) const option = ctx.options.getString('pregunta', true)
const forusr = options[1].getMember('para') const forusr = ctx.options.getMember('para')
const filter = mctags.filter(obj => obj.title.includes(option))[0] const filter = mctags.filter(obj => obj.title.includes(option))[0]
const embed = new EmbedBuilder() const embed = new EmbedBuilder()

View File

@@ -1,15 +1,10 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import google from 'googlethis' import google from 'googlethis'
import { ApplicationCommandOptionType } from 'discord.js'; import { ApplicationCommandOptionType } from 'discord.js';
/*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"
*/
export default commandModule({ export default commandModule({
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Busca cosas en Google.', description: 'Busca cosas en Google.',
//alias : [], //alias : [],
options: [ options: [
@@ -20,9 +15,9 @@ export default commandModule({
required: true, required: true,
} }
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
await ctx.interaction.deferReply() await ctx.interaction.deferReply()
const prompt = options[1].getString('busqueda', true) const prompt = ctx.options.getString('busqueda', true)
const search = await Promise.all((await google.search(prompt)).results.map(res => { const search = await Promise.all((await google.search(prompt)).results.map(res => {
return `[${res.title}](<${res.url}>)` return `[${res.title}](<${res.url}>)`

View File

@@ -7,13 +7,13 @@ import sharp from 'sharp';
export default commandModule({ export default commandModule({
name: 'Clasifica una imagen', name: 'Clasifica una imagen',
type: CommandType.CtxMsg, type: CommandType.CtxMsg,
plugins: [publish()], plugins: [],
execute: async (ctx) => { execute: async (ctx) => {
await ctx.deferReply() await ctx.deferReply()
if (ctx.targetMessage.attachments.size === 0) return ctx.editReply('No hay ninguna imagen para clasificar!'); if (ctx.targetMessage.attachments.size === 0) return ctx.editReply('No hay ninguna imagen para clasificar!');
const image = ctx.targetMessage.attachments.first(); const image = ctx.targetMessage.attachments.first()!;
if (!image.contentType.startsWith('image/') && image.contentType !== 'image/gif') return ctx.editReply('El archivo no es una imagen!'); if (!image.contentType!.startsWith('image/') && image.contentType !== 'image/gif') return ctx.editReply('El archivo no es una imagen!');
const imageBuffer = await fetch(image.url).then(async res => await res.arrayBuffer()); const imageBuffer = await fetch(image.url).then(async res => await res.arrayBuffer());
const compressed = sharp(imageBuffer) const compressed = sharp(imageBuffer)
@@ -34,10 +34,10 @@ export default commandModule({
if (request.errors.length > 0) return ctx.editReply(`Hubo un error! ${codeBlock(JSON.stringify(request.errors))}`); if (request.errors.length > 0) return ctx.editReply(`Hubo un error! ${codeBlock(JSON.stringify(request.errors))}`);
// all canvas stuff, this was fun to make // all canvas stuff, this was fun to make
const canvas = createCanvas(metadata.width, metadata.height); const canvas = createCanvas(metadata.width!, metadata.height!);
const ctxCanvas = canvas.getContext('2d'); const ctxCanvas = canvas.getContext('2d');
const img = await loadImage(image.url); const img = await loadImage(image.url);
ctxCanvas.drawImage(img, 0, 0, metadata.width, metadata.height); ctxCanvas.drawImage(img, 0, 0, metadata.width!, metadata.height!);
ctxCanvas.font = '40px sans-serif'; ctxCanvas.font = '40px sans-serif';
ctxCanvas.fillStyle = 'red'; ctxCanvas.fillStyle = 'red';
ctxCanvas.strokeStyle = 'red'; ctxCanvas.strokeStyle = 'red';

View File

@@ -1,15 +1,14 @@
import { commandModule, CommandType } from '@sern/handler'; import { commandModule, CommandType } from '@sern/handler';
import { ApplicationCommandOptionType, bold, codeBlock, EmbedBuilder, inlineCode } from 'discord.js'; import { ApplicationCommandOptionType, bold, codeBlock, EmbedBuilder, inlineCode } from 'discord.js';
import { publish } from '../../plugins/publish.js';
import fs from 'node:fs/promises' import fs from 'node:fs/promises'
import { ICFile } from '../../util/infinitecraft/decompress.js'; import { ICFile } from '../../util/infinitecraft/decompress.js';
import Finder from '../../util/infinitecraft/finder.js'; import Finder from '../../util/infinitecraft/finder.js';
const recipeFile = JSON.parse(await fs.readFile('./util/infinitecraft/recipes.json', 'utf-8')) as ICFile; const recipeFile = JSON.parse(await fs.readFile('./assets/icRecipes.json', 'utf-8')) as ICFile;
export default commandModule({ export default commandModule({
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Descifra con un algoritmo cómo llegar a la receta de un objeto en InfiniteCraft', description: 'Descifra con un algoritmo cómo llegar a la receta de un objeto en InfiniteCraft',
options: [ options: [
{ {
@@ -36,14 +35,14 @@ export default commandModule({
} }
} }
], ],
execute: async (ctx, [, options]) => { execute: async (ctx) => {
await ctx.interaction.deferReply() await ctx.interaction.deferReply()
const object = options.getString('objeto', true) const object = ctx.options.getString('objeto', true)
if (object === 'SSError') return ctx.reply({ if (object === 'SSError') return ctx.reply({
content: 'Has escogido el mensaje de error 💀', content: 'Has escogido el mensaje de error 💀',
ephemeral: true ephemeral: true
}); });
if (!recipeFile.items.includes(options.getString('objeto', true))) return ctx.reply({ if (!recipeFile.items.includes(ctx.options.getString('objeto', true))) return ctx.reply({
content: 'No se encontró el objeto. Asegúrate de escogerlo del autocompletado.', content: 'No se encontró el objeto. Asegúrate de escogerlo del autocompletado.',
ephemeral: true ephemeral: true
}); });
@@ -78,8 +77,9 @@ export default commandModule({
}); });
const recipe = path.map(({ first, second, result }) => `${first} + ${second} = ${result}`).join('\n') const recipe = path.map(({ first, second, result }) => `${first} + ${second} = ${result}`).join('\n')
let paste: string | undefined;
if (recipe.length >= 1500) { if (recipe.length >= 1500) {
var paste = await fetch('https://fb.srizan.dev/paste', { paste = await fetch('https://fb.srizan.dev/paste', {
method: 'POST', method: 'POST',
body: recipe body: recipe
}).then(async res => await res.text()) }).then(async res => await res.text())

View File

@@ -1,5 +1,4 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import Genius from 'genius-lyrics' import Genius from 'genius-lyrics'
import { ActionRowBuilder, ApplicationCommandOptionType, ButtonBuilder, ButtonStyle, EmbedBuilder } from 'discord.js'; import { ActionRowBuilder, ApplicationCommandOptionType, ButtonBuilder, ButtonStyle, EmbedBuilder } from 'discord.js';
@@ -7,7 +6,7 @@ const genius = new Genius.Client(process.env.GENIUS)
export default commandModule({ export default commandModule({
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Busca la letra de una canción (Genius)', description: 'Busca la letra de una canción (Genius)',
//alias : [], //alias : [],
options: [ options: [
@@ -34,9 +33,9 @@ export default commandModule({
} }
} }
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
await ctx.interaction.deferReply({ ephemeral: true }) await ctx.interaction.deferReply({ ephemeral: true })
const prompt = options[1].getString('busqueda', true) const prompt = ctx.options.getString('busqueda', true)
const result = await genius.songs.get(Number(prompt)) const result = await genius.songs.get(Number(prompt))

View File

@@ -1,17 +1,13 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { createAudioPlayer, createAudioResource, DiscordGatewayAdapterCreator, joinVoiceChannel } from "@discordjs/voice"; import { createAudioPlayer, createAudioResource, DiscordGatewayAdapterCreator, joinVoiceChannel } from "@discordjs/voice";
import got from "got"; import got from "got";
import { ApplicationCommandOptionType, EmbedBuilder } from "discord.js"; import { ApplicationCommandOptionType, EmbedBuilder } from "discord.js";
/* const choices = ['Rock FM', 'Cadena 100', 'Cadena Dial', 'Gensokyo Radio', 'BBC 1', 'RNE 1', 'RNE 5', 'Los 40'];
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"
*/
export default commandModule({ export default commandModule({
name: 'radio', name: 'radio',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Reproduce la radio', description: 'Reproduce la radio',
options: [ options: [
{ {
@@ -24,7 +20,6 @@ export default commandModule({
onEvent: [], onEvent: [],
async execute(ctx){ async execute(ctx){
const focusedValue = ctx.options.getFocused(); const focusedValue = ctx.options.getFocused();
const choices = ['Rock FM', 'Cadena 100', 'Cadena Dial', 'Gensokyo Radio', 'BBC 1', 'RNE 1', 'RNE 5', 'Los 40', 'Flaixbac', 'FlaixFM'];
const filtered = choices.filter(choice => choice.startsWith(focusedValue)); const filtered = choices.filter(choice => choice.startsWith(focusedValue));
await ctx.respond( await ctx.respond(
filtered.map(choice => ({ name: choice, value: choice })), filtered.map(choice => ({ name: choice, value: choice })),
@@ -33,8 +28,9 @@ export default commandModule({
} }
} }
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
const radioname = options[1].getString("reproducir", true) const radioname = ctx.options.getString("reproducir", true)
if (!choices.includes(radioname)) return await ctx.reply('Asegúrate de escoger una radio de la lista.')
const embed = new EmbedBuilder() const embed = new EmbedBuilder()
.setColor("Green") .setColor("Green")
.setTitle(`Reproduciendo ${radioname} en Vinci Radio.`) .setTitle(`Reproduciendo ${radioname} en Vinci Radio.`)
@@ -44,18 +40,14 @@ export default commandModule({
.setTitle(`Radio ${radioname} no encontrada.`) .setTitle(`Radio ${radioname} no encontrada.`)
.setDescription(`La radio no ha sido encontrada, asegúrate que la radio está escogida de la lista.`); .setDescription(`La radio no ha sido encontrada, asegúrate que la radio está escogida de la lista.`);
async function playRadio(radioname: string, isFlaix?: boolean) { async function playRadio(radioname: string) {
const stream = got.stream(radioname) const stream = got.stream(radioname)
const connection = joinVoiceChannel({adapterCreator: ctx.interaction.guild!.voiceAdapterCreator as DiscordGatewayAdapterCreator, channelId: '1008730592835281009',guildId: '928018226330337280',selfDeaf: true}); const connection = joinVoiceChannel({adapterCreator: ctx.interaction.guild!.voiceAdapterCreator as DiscordGatewayAdapterCreator, channelId: '1008730592835281009',guildId: '928018226330337280',selfDeaf: true});
const resource = createAudioResource(stream, { inlineVolume: true }); const resource = createAudioResource(stream, { inlineVolume: true });
const player = createAudioPlayer(); const player = createAudioPlayer();
connection.subscribe(player) connection.subscribe(player)
player.play(resource) player.play(resource)
if (isFlaix === true) { resource.volume!.setVolume(0.7)
resource.volume!.setVolume(0.3)
} else {
resource.volume!.setVolume(0.7)
}
await ctx.reply({embeds: [embed], ephemeral: true}) await ctx.reply({embeds: [embed], ephemeral: true})
} }
@@ -84,12 +76,6 @@ export default commandModule({
case 'Gensokyo Radio': { case 'Gensokyo Radio': {
playRadio('https://stream.gensokyoradio.net/3') playRadio('https://stream.gensokyoradio.net/3')
} break; } break;
case 'Flaixbac': {
playRadio('https://nodo07-cloud01.streaming-pro.com:8005/flaixbac.mp3', true)
} break;
case 'FlaixFM': {
playRadio('https://nodo07-cloud01.streaming-pro.com:8001/flaixfm.mp3', true)
} break;
default: { default: {
await ctx.reply({embeds: [notFoundEmbed], ephemeral: true}) await ctx.reply({embeds: [notFoundEmbed], ephemeral: true})
} break; } break;

View File

@@ -1,13 +1,13 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"; import { ownerOnly } from "#plugins";
import { ActionRowBuilder, ApplicationCommandOptionType, ChannelType, Collection, EmbedBuilder, Role, SelectMenuBuilder, TextChannel } from "discord.js"; import { ActionRowBuilder, ApplicationCommandOptionType, ChannelType, ChatInputCommandInteraction, Collection, EmbedBuilder, Role, StringSelectMenuBuilder, TextChannel } from "discord.js";
import { Resolver } from "../../util/resolver.js"; import { Resolver } from "../../util/resolver.js";
export default commandModule({ export default commandModule({
name: 'rolemenu', name: 'rolemenu',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish(), ownerOnly()], plugins: [ownerOnly()],
description: 'ADMIN: Spawnea un menú de roles', description: 'ADMIN: Spawnea un menú de roles',
//alias : [], //alias : [],
options: [ options: [
@@ -31,11 +31,13 @@ export default commandModule({
required: true, required: true,
}, },
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
const channel = options[1].getChannel("channel", true) as TextChannel; const channel = ctx.options.getChannel("channel", true) as unknown as TextChannel;
const role = new Resolver(options[1].getString("role", true), ctx.interaction) if (!channel.isSendable()) return ctx.reply("Channel is not sendable");
// @ts-ignore it should still be a correct interaction
const role = new Resolver(ctx.options.getString("role", true), ctx.interaction)
.roles; .roles;
const message = options[1].getString("message", true); const message = ctx.options.getString("message", true);
if (role.size > 25) return ctx.reply("Too many roles"); if (role.size > 25) return ctx.reply("Too many roles");
@@ -50,6 +52,7 @@ export default commandModule({
); );
} }
await ctx.interaction.deferReply(); await ctx.interaction.deferReply();
// @ts-ignore it should still be a textchannel
const row = createMenu(channel, role); const row = createMenu(channel, role);
const embed = new EmbedBuilder() const embed = new EmbedBuilder()
.setTitle(message) .setTitle(message)
@@ -67,7 +70,7 @@ export default commandModule({
function createMenu(channel: TextChannel, role: Collection<string, Role>) { function createMenu(channel: TextChannel, role: Collection<string, Role>) {
if (!channel || !role) throw new Error("Missing channel or role"); if (!channel || !role) throw new Error("Missing channel or role");
const menu = new SelectMenuBuilder() const menu = new StringSelectMenuBuilder()
.setCustomId("role-menu") .setCustomId("role-menu")
.setMaxValues(role.size) .setMaxValues(role.size)
.setMinValues(0) .setMinValues(0)
@@ -80,6 +83,6 @@ function createMenu(channel: TextChannel, role: Collection<string, Role>) {
}; };
}) })
); );
const row = new ActionRowBuilder<SelectMenuBuilder>().setComponents(menu); const row = new ActionRowBuilder<StringSelectMenuBuilder>().setComponents(menu);
return row; return row;
}; };

View File

@@ -1,13 +1,13 @@
import { commandModule, CommandType } from "@sern/handler"; import { commandModule, CommandType } from "@sern/handler";
import axios, { AxiosError, AxiosResponse } from "axios"; import axios, { AxiosResponse } from "axios";
import { ApplicationCommandOptionType } from "discord.js"; import { ApplicationCommandOptionType } from "discord.js";
import { publish } from "#plugins"; import { disable } from "#plugins";
export default commandModule({ export default commandModule({
name: "acortar", name: "acortar",
type: CommandType.Slash, type: CommandType.Slash,
plugins: [ plugins: [
publish(), disable()
], ],
description: "Acorta una URL a vinci.tk", description: "Acorta una URL a vinci.tk",
options: [ options: [
@@ -20,7 +20,7 @@ export default commandModule({
], ],
//alias : [], //alias : [],
execute: async (ctx, options) => { execute: async (ctx, options) => {
const url = options[1].getString("url", true); const url = ctx.options.getString("url", true);
const request = await axios( const request = await axios(
`https://vinci.tk/yourls-api.php?signature=${process.env.YOURLS_KEY}&action=shorturl&format=json&url=${url}`, `https://vinci.tk/yourls-api.php?signature=${process.env.YOURLS_KEY}&action=shorturl&format=json&url=${url}`,
{ {

View File

@@ -1,14 +1,14 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins"; import { disable } from "#plugins";
import { ownerOnly } from "#plugins";
import { EmbedBuilder } from "discord.js"; import { EmbedBuilder } from "discord.js";
import axios from "axios"; import axios from "axios";
// @ts-ignore
import prettySeconds from 'pretty-seconds-spanish' import prettySeconds from 'pretty-seconds-spanish'
export default commandModule({ export default commandModule({
name: 'stats', name: 'stats',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [disable()],
description: 'Enseña estadísticas del bot.', description: 'Enseña estadísticas del bot.',
//alias : [], //alias : [],
options: [], options: [],

View File

@@ -1,13 +1,11 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { ActionRowBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, ModalActionRowComponentBuilder } from 'discord.js' import { ActionRowBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, ModalActionRowComponentBuilder } from 'discord.js'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins";
export default commandModule({ export default commandModule({
name: 'sugerencias', name: 'sugerencias',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Envia una sugerencia.', description: 'Envia una sugerencia.',
//alias : [], //alias : [],
execute: async (ctx) => { execute: async (ctx) => {

View File

@@ -1,18 +1,12 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins";
import axios from 'axios'; import axios from 'axios';
import { readFileSync } from 'node:fs'
import { ActionRowBuilder, ApplicationCommandOptionType, ButtonBuilder, ButtonStyle, ComponentType, EmbedBuilder } from 'discord.js'; import { ActionRowBuilder, ApplicationCommandOptionType, ButtonBuilder, ButtonStyle, ComponentType, EmbedBuilder } from 'discord.js';
const choices = ['es', 'en', 'fr', 'de', 'hi', 'it', 'ja', 'ko', 'pl'] const choices = ['es', 'en', 'fr', 'de', 'hi', 'it', 'ja', 'ko', 'pl']
/*
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"
*/
export default commandModule({ export default commandModule({
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
// , '928018226330337280' // , '928018226330337280'
description: 'Traduce lo que quieras!', description: 'Traduce lo que quieras!',
//alias : [], //alias : [],
@@ -44,9 +38,9 @@ export default commandModule({
} }
} }
], ],
execute: async (ctx, options) => { execute: async (ctx) => {
const langToTranslate = options[1].getString('idioma', true) const langToTranslate = ctx.options.getString('idioma', true)
const stringToTranslate = options[1].getString('frase', true) const stringToTranslate = ctx.options.getString('frase', true)
if (choices.indexOf(langToTranslate) === -1) if (choices.indexOf(langToTranslate) === -1)
return ctx.reply({content: 'Elige un idioma del autocompletado.'}) return ctx.reply({content: 'Elige un idioma del autocompletado.'})

View File

@@ -1,15 +1,15 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins"; // @ts-ignore
import prettySeconds from 'pretty-seconds-spanish' import prettySeconds from 'pretty-seconds-spanish'
export default commandModule({ export default commandModule({
name: 'uptime', name: 'uptime',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Enseña el tiempo que ha estado encendido el bot.', description: 'Enseña el tiempo que ha estado encendido el bot.',
//alias : [], //alias : [],
options: [], options: [],
execute: async (ctx, options) => { execute: async (ctx) => {
// const uptime = prettyMilliseconds(ctx.client.uptime!) // const uptime = prettyMilliseconds(ctx.client.uptime!)
const uptime = prettySeconds(process.uptime()) const uptime = prettySeconds(process.uptime())
await ctx.reply(`El bot lleva encendido ${uptime}`); await ctx.reply(`El bot lleva encendido ${uptime}`);

View File

@@ -1,11 +1,10 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins"; import { ApplicationCommandOptionType, AutocompleteInteraction, CacheType, CommandInteractionOptionResolver } from 'discord.js';
import { ApplicationCommandOptionType } from 'discord.js'; import { getWikipedia, searchWikipedia } from '../../util/wikipedia.js';
import { getWikipedia, searchWikipedia, SearchWikipediaObject } from '../../util/wikipedia.js';
export default commandModule({ export default commandModule({
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'Busca cosas por wikipedia', description: 'Busca cosas por wikipedia',
//alias : [], //alias : [],
options: [ options: [
@@ -23,7 +22,7 @@ export default commandModule({
command: { command: {
onEvent: [], onEvent: [],
execute: async (ctx) => { execute: async (ctx) => {
const search = await searchWikipedia('es', ctx) const search = await searchWikipedia('es', ctx as unknown as AutocompleteInteraction)
await ctx.respond( await ctx.respond(
search.map(res => ({ name: res.title.toString(), value: res.pageid.toString() })) search.map(res => ({ name: res.title.toString(), value: res.pageid.toString() }))
) )
@@ -46,7 +45,7 @@ export default commandModule({
command: { command: {
onEvent: [], onEvent: [],
execute: async (ctx) => { execute: async (ctx) => {
const search = await searchWikipedia('en', ctx) const search = await searchWikipedia('en', ctx as unknown as AutocompleteInteraction)
await ctx.respond( await ctx.respond(
search.map(res => ({ name: res.title.toString(), value: res.pageid.toString() })) search.map(res => ({ name: res.title.toString(), value: res.pageid.toString() }))
) )
@@ -56,13 +55,14 @@ export default commandModule({
] ]
} }
], ],
execute: async (ctx, [, options]) => { execute: async (ctx) => {
switch (options.getSubcommand()) { const options = ctx.options as unknown as CommandInteractionOptionResolver<CacheType>
switch (ctx.options.getSubcommand()) {
case 'español': { case 'español': {
getWikipedia('es', ctx, options) getWikipedia('es', ctx, options);
} break; } break;
case 'ingles': { case 'ingles': {
getWikipedia('en', ctx, options) getWikipedia('en', ctx, options);
} break; } break;
} }
}, },

View File

@@ -1,12 +1,12 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins";; import { ownerOnly } from "#plugins";;
import { ApplicationCommandOptionType, TextChannel } from 'discord.js' import { ApplicationCommandOptionType, TextChannel } from 'discord.js'
export default commandModule({ export default commandModule({
name: 'prune', name: 'prune',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish(), ownerOnly()], plugins: [ownerOnly()],
description: 'ADMIN: Elimina hasta 100 mensajes', description: 'ADMIN: Elimina hasta 100 mensajes',
options: [{ options: [{
name: 'numero', name: 'numero',
@@ -17,14 +17,14 @@ export default commandModule({
max_value: 100 max_value: 100
}], }],
//alias : [], //alias : [],
execute: async (ctx, options) => { execute: async (ctx) => {
try { try {
const amount = options[1].getNumber('numero', true) as number const amount = ctx.options.getNumber('numero', true) as number
(ctx.channel as TextChannel).bulkDelete(amount).catch(err => { (ctx.channel as unknown as TextChannel).bulkDelete(amount).catch(err => {
console.error(err); console.error(err);
ctx.reply({content: 'Ha habido un error eliminando mensajes! (mira la consola, Sr Izan)', ephemeral: true});}); ctx.reply({content: 'Ha habido un error eliminando mensajes! (mira la consola, Sr Izan)', ephemeral: true});});
await ctx.reply({content: `Se han eliminado ${amount} mensajes.`}) await ctx.reply({content: `Se han eliminado ${amount} mensajes.`})
const sendToMods = ctx.client.guilds.cache.get(process.env.GUILDID!)!.channels.cache.get(process.env.MODLOGS_CHANNEL!) as TextChannel const sendToMods = ctx.client.guilds.cache.get(process.env.GUILDID!)!.channels.cache.get(process.env.MODLOGS_CHANNEL!) as unknown as TextChannel
await sendToMods.send({content: `Se han eliminado ${amount} mensajes en ${ctx.channel}\nEfectuado por ${ctx.user}.`}) await sendToMods.send({content: `Se han eliminado ${amount} mensajes en ${ctx.channel}\nEfectuado por ${ctx.user}.`})
} catch { } catch {
ctx.reply({content: 'Ha habido un error eliminando mensajes! Error reportado automáticamente.', ephemeral: true})}; ctx.reply({content: 'Ha habido un error eliminando mensajes! Error reportado automáticamente.', ephemeral: true})};

View File

@@ -1,12 +1,12 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins"; import { ownerOnly } from "#plugins";
import { ApplicationCommandOptionType, TextChannel } from "discord.js"; import { ApplicationCommandOptionType, TextChannel } from "discord.js";
export default commandModule({ export default commandModule({
name: 'slowmode', name: 'slowmode',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish(), ownerOnly()], plugins: [ownerOnly()],
description: 'ADMIN: Pon modo lento a canales de texto', description: 'ADMIN: Pon modo lento a canales de texto',
options: [ options: [
{ {
@@ -23,15 +23,15 @@ export default commandModule({
} }
], ],
//alias : [], //alias : [],
execute: async (ctx, options) => { execute: async (ctx) => {
try { try {
const seconds = options[1].getNumber("segundos", true); const seconds = ctx.options.getNumber("segundos", true);
const reason = options[1].getString("razon", true); const reason = ctx.options.getString("razon", true);
(ctx.channel as TextChannel).setRateLimitPerUser(seconds, reason) (ctx.channel as unknown as TextChannel).setRateLimitPerUser(seconds, reason)
ctx.reply({content: `Se han añadido ${seconds} segundos de modo lento al canal de voz actual`}) ctx.reply({content: `Se han añadido ${seconds} segundos de modo lento al canal de voz actual`})
const sendToMods = ctx.client.guilds.cache.get(process.env.GUILDID!)!.channels.cache.get(process.env.MODLOGS_CHANNEL!) as TextChannel const sendToMods = ctx.client.guilds.cache.get(process.env.GUILDID!)!.channels.cache.get(process.env.MODLOGS_CHANNEL!) as unknown as TextChannel
await sendToMods.send({content: `Se ha aplicado modo lento al canal ${ctx.channel}.\nEfectuado por ${ctx.user} con ${seconds} segundos de retardo.\nRazón: ${reason}`}) await sendToMods.send({content: `Se ha aplicado modo lento al canal ${ctx.channel}.\nEfectuado por ${ctx.user} con ${seconds} segundos de retardo.\nRazón: ${reason}`})
} catch { } catch {
ctx.reply({content: `No se ha podido aplicar modo lento al canal.`}) ctx.reply({content: `No se ha podido aplicar modo lento al canal.`})

View File

@@ -1,11 +1,11 @@
import { commandModule, CommandType } from '@sern/handler' import { commandModule, CommandType } from '@sern/handler'
import { publish } from "#plugins";
import { ownerOnly } from "#plugins" import { ownerOnly } from "#plugins"
export default commandModule({ export default commandModule({
name: 'ping', name: 'ping',
type: CommandType.Slash, type: CommandType.Slash,
plugins: [publish()], plugins: [],
description: 'A ping command', description: 'A ping command',
//alias : [], //alias : [],
options: [], options: [],

12
src/config.ts Normal file
View File

@@ -0,0 +1,12 @@
//CONFIG FILE: export only data here and do not cause side effects. Feel free to add your own configuration to this file.
//commands directory. REQUIRED
export const commands = './dist/commands'
// events directory.
export const events = './dist/events'
// schedule tasks and declare them here
//export const tasks = './dist/tasks'
// defaultPrefix: if omitted, sern will disable all text/prefix commands
//export const defaultPrefix = '?'

24
src/dependencies.d.ts vendored Normal file
View File

@@ -0,0 +1,24 @@
/*
* This file serves as intellisense for sern projects.
* Types are declared here for dependencies to function properly
* Service(s) api rely on this file to provide a better developer experience.
*/
import type { CoreDependencies } from '@sern/handler';
import type { Client } from 'discord.js';
import type { Publisher } from '@sern/publisher';
import type Spotify from 'spotify-api.js';
/**
* Note: You usually would not need to modify this unless there is an urgent need to break the contracts provided.
* You would need to modify this to add your custom Services, however.
*/
declare global {
interface Dependencies extends CoreDependencies {
'@sern/client': Client;
'publisher': Publisher;
'spotify-api-client': Spotify.Client;
}
}
export {}

View File

@@ -1,11 +1,10 @@
import { EventType, eventModule } from '@sern/handler'; import { EventType, discordEvent, eventModule } from '@sern/handler';
import { EmbedBuilder, Message } from 'discord.js'; import { EmbedBuilder, Message } from 'discord.js';
import db from '../schemas/afk.js'; import db from '../schemas/afk.js';
export default eventModule({ export default discordEvent({
type: EventType.Discord,
name: 'messageCreate', name: 'messageCreate',
execute: async (message: Message) => { execute: async (message) => {
const dbEntries = await db.find() const dbEntries = await db.find()
dbEntries.forEach(async (doc) => { dbEntries.forEach(async (doc) => {

View File

@@ -1,8 +1,6 @@
import { discordEvent } from '@sern/handler'; import { discordEvent } from '@sern/handler';
import { TextChannel } from 'discord.js';
import db from '../schemas/chatgpt.js'; import db from '../schemas/chatgpt.js';
import { fetchEventSource } from '@ai-zen/node-fetch-event-source'; import { fetchEventSource } from '@ai-zen/node-fetch-event-source';
import { devMode } from '../index.js';
export default discordEvent({ export default discordEvent({
name: 'messageCreate', name: 'messageCreate',

View File

@@ -1,12 +1,13 @@
import { discordEvent } from '@sern/handler'; import { discordEvent } from '@sern/handler';
import { ThreadChannel } from 'discord.js'; import { PublicThreadChannel } from 'discord.js';
import database from '../schemas/chatgpt.js'; import database from '../schemas/chatgpt.js';
import { fetchEventSource } from '@ai-zen/node-fetch-event-source'; import { fetchEventSource } from '@ai-zen/node-fetch-event-source';
export default discordEvent({ export default discordEvent({
name: 'messageCreate', name: 'messageCreate',
async execute(message) { async execute(message) {
const thread = message.channel as ThreadChannel // @ts-ignore idk man
const thread = message.channel as PublicThreadChannel<false>;
if (thread.parentId !== process.env.CHATGPT_CHANNEL) return; if (thread.parentId !== process.env.CHATGPT_CHANNEL) return;
if (message.author.bot) return; if (message.author.bot) return;
if (message.content.includes('v!ig')) return; if (message.content.includes('v!ig')) return;

View File

@@ -9,7 +9,7 @@ export default discordEvent({
if (!message.content.includes('https://open.spotify.com/intl-es/track')) return; if (!message.content.includes('https://open.spotify.com/intl-es/track')) return;
const index = message.content.indexOf("https://open.spotify.com/intl-es/track"); const index = message.content.indexOf("https://open.spotify.com/intl-es/track");
let link: string let link: string = ''
if (index !== -1) { if (index !== -1) {
let endIndex = message.content.indexOf(" ", index); let endIndex = message.content.indexOf(" ", index);
if (endIndex === -1) { if (endIndex === -1) {
@@ -19,11 +19,11 @@ export default discordEvent({
} }
const croppedUrl = removeURLParameter(link.replace('intl-es/', '').replaceAll(/([^:]\/)\/+/g, "$1"), 'si'); const croppedUrl = removeURLParameter(link.replace('intl-es/', '').replaceAll(/([^:]\/)\/+/g, "$1"), 'si');
const song = await spotify.tracks.get(croppedUrl.split('/').pop()); const song = await spotify.tracks.get(croppedUrl.split('/').pop()!);
await message.delete(); await message.delete();
message.channel.send({ message.channel.send({
content: `Oye <@${message.author.id}>, tu canción \`${song.name}\` de \`${song.artists.map(a => a.name).join(', ')}\` es muy buena, pero si quitas \`intl-es\` es mejor.\n${croppedUrl}`, content: `Oye <@${message.author.id}>, tu canción \`${song!.name}\` de \`${song!.artists.map(a => a.name).join(', ')}\` es muy buena, pero si quitas \`intl-es\` es mejor.\n${croppedUrl}`,
}) })
} }
}) })

View File

@@ -6,4 +6,4 @@ export default eventModule({
execute(err) { execute(err) {
console.log(err); console.log(err);
} }
}) })

View File

@@ -1,20 +1,19 @@
import { EmbedBuilder, GuildMember, TextChannel } from "discord.js"; import { EmbedBuilder, GuildMember, TextChannel } from "discord.js";
import { EventType, eventModule } from "@sern/handler"; import { EventType, discordEvent, eventModule } from "@sern/handler";
export default eventModule({ export default discordEvent({
type: EventType.Discord,
name: 'guildMemberAdd', name: 'guildMemberAdd',
execute(member: GuildMember) { execute(member) {
if (member.guild.id !== process.env.GUILDID) return; if (member.guild.id !== process.env.GUILDID) return;
const newMemberEmbed = new EmbedBuilder() const newMemberEmbed = new EmbedBuilder()
.setColor("Random") .setColor("Random")
.setTitle("Nuevo miembro!") .setTitle("Nuevo miembro!")
.setDescription(`${member.user} acaba de entrar al servidor!`) .setDescription(`${member.user} acaba de entrar al servidor!`)
.setThumbnail(member.user.displayAvatarURL()) .setThumbnail(member.user.displayAvatarURL())
.setTimestamp(); .setTimestamp();
const channel = member.client.guilds.cache.get(process.env.GUILDID!)!.channels.cache.get(process.env.JOINSANDLEAVES_CHANNEL!) as TextChannel const channel = member.client.guilds.cache.get(process.env.GUILDID!)!.channels.cache.get(process.env.JOINSANDLEAVES_CHANNEL!) as unknown as TextChannel
channel.send({embeds: [newMemberEmbed]}) channel.send({embeds: [newMemberEmbed]})
} }
}); });

View File

@@ -1,20 +1,19 @@
import { EmbedBuilder, GuildMember, TextChannel } from "discord.js"; import { EmbedBuilder, GuildMember, TextChannel } from "discord.js";
import { EventType, eventModule } from "@sern/handler"; import { EventType, discordEvent, eventModule } from "@sern/handler";
export default eventModule({ export default discordEvent({
type: EventType.Discord,
name: 'guildMemberRemove', name: 'guildMemberRemove',
execute(member: GuildMember) { execute(member) {
if (member.guild.id !== process.env.GUILDID) return; if (member.guild.id !== process.env.GUILDID) return;
const leaveEmbed = new EmbedBuilder() const leaveEmbed = new EmbedBuilder()
.setColor("Random") .setColor("Random")
.setTitle("Un miembro se ha ido :(") .setTitle("Un miembro se ha ido :(")
.setDescription(`${member.user} acaba de salir del servidor!`) .setDescription(`${member.user} acaba de salir del servidor!`)
.setThumbnail(member.user.displayAvatarURL()) .setThumbnail(member.user.displayAvatarURL())
.setTimestamp(); .setTimestamp();
const channel = member.client.guilds.cache.get(process.env.GUILDID!)!.channels.cache.get(process.env.JOINSANDLEAVES_CHANNEL!) as TextChannel const channel = member.client.guilds.cache.get(process.env.GUILDID!)!.channels.cache.get(process.env.JOINSANDLEAVES_CHANNEL!) as unknown as TextChannel
channel.send({embeds: [leaveEmbed]}) channel.send({embeds: [leaveEmbed]})
} }
}); });

View File

@@ -1,4 +1,4 @@
import { DefaultLogging, makeDependencies, single, Singleton } from '@sern/handler'; import { makeDependencies } from '@sern/handler';
import { ActivityOptions, ActivityType } from 'discord.js'; import { ActivityOptions, ActivityType } from 'discord.js';
import { Client, GatewayIntentBits } from 'discord.js'; import { Client, GatewayIntentBits } from 'discord.js';
import { Sern } from '@sern/handler'; import { Sern } from '@sern/handler';
@@ -9,7 +9,8 @@ import { setIntervalAsync } from 'set-interval-async';
import birthdays from './util/birthdays.js'; import birthdays from './util/birthdays.js';
import minecraftstatus from './util/minecraftstatus.js'; import minecraftstatus from './util/minecraftstatus.js';
import Spotify from 'spotify-api.js'; import Spotify from 'spotify-api.js';
// import giveawaychecker from './util/giveawaychecker.js'; import { Publisher } from '@sern/publisher';
import * as sernconfig from './config.js'
export let devMode: boolean export let devMode: boolean
if (process.argv[2] === '--dev') { if (process.argv[2] === '--dev') {
@@ -40,22 +41,17 @@ const spotifyClient = await Spotify.Client.create({
token: { clientID: process.env.SPOTIFY_CLIENT!, clientSecret: process.env.SPOTIFY_SECRET! }, token: { clientID: process.env.SPOTIFY_CLIENT!, clientSecret: process.env.SPOTIFY_SECRET! },
}) })
interface MyDependencies extends Dependencies { await makeDependencies(({ add }) => {
'@sern/client' : Singleton<Client>; add('@sern/client', client);
'@sern/logger' : Singleton<DefaultLogging> add('publisher', deps => new Publisher(
} deps['@sern/modules'],
deps['@sern/emitter'],
await makeDependencies<MyDependencies>({ deps['@sern/logger']!
build: (root) => root ));
.add({ '@sern/client': single(() => client) }) add('spotify-api-client', spotifyClient);
.add({ 'spotify-api-client': single(() => spotifyClient) })
}); });
Sern.init({ Sern.init(sernconfig);
commands: 'dist/commands',
events: 'dist/events',
defaultPrefix: process.env.PREFIX,
});
client.on('ready', async () => { client.on('ready', async () => {
console.log('Logged on!'); console.log('Logged on!');
@@ -71,7 +67,7 @@ client.on('ready', async () => {
{ name: 'ahora v1.0!', type: ActivityType.Playing }, { name: 'ahora v1.0!', type: ActivityType.Playing },
] as ActivityOptions[]; ] as ActivityOptions[];
const randomStatus = statuses[Math.floor(Math.random() * statuses.length)]; const randomStatus = statuses[Math.floor(Math.random() * statuses.length)];
client.user.setActivity(randomStatus); client.user!.setActivity(randomStatus);
}, 10000); }, 10000);
if (!devMode) { if (!devMode) {
@@ -93,4 +89,4 @@ client.on('ready', async () => {
// export const scamLinks = await axios.get('https://api.hyperphish.com/gimme-domains').then(res => res.data as Array<string>) // export const scamLinks = await axios.get('https://api.hyperphish.com/gimme-domains').then(res => res.data as Array<string>)
client.login(process.env.TOKEN); client.login();

80
src/plugins/disable.ts Normal file
View File

@@ -0,0 +1,80 @@
//@ts-nocheck
/**
* @plugin
* Disables a command entirely, for whatever reasons you may need.
*
* @author @jacoobes [<@182326315813306368>]
* @author @Peter-MJ-Parker [<@371759410009341952>]
* @version 2.1.0
* @example
* ```ts
* import { disable } from "../plugins/disable";
* import { commandModule } from "@sern/handler";
* export default commandModule({
* plugins: [ disable() ],
* execute: (ctx) => {
* //your code here
* }
* })
* ```
* @end
*/
import { CommandType, CommandControlPlugin, controller } from "@sern/handler";
import { InteractionReplyOptions, MessageReplyOptions } from "discord.js";
export function disable(
onFail?:
| string
| Omit<InteractionReplyOptions, "fetchReply">
| MessageReplyOptions
) {
return CommandControlPlugin<CommandType.Both>(async (ctx, [args]) => {
if (onFail !== undefined) {
switch (args) {
case "text":
try {
//reply to text command
const msg = await ctx.reply(onFail);
setTimeout(() => {
//deletes the bots reply to the user
msg.delete();
//deletes the original authors message (text command).
ctx.message.delete();
//waits 5 seconds before deleting messages
}, 5000);
} catch (error) {
console.log(
"Could not delete disabled response due to: " +
error
);
}
break;
case "slash":
//response to say the command is disabled with users response.
let reply = await ctx.reply(onFail);
try {
setTimeout(async () => {
await reply.delete();
}, 5000);
} catch (error) {
console.log(
"Could not delete disabled response due to it being ephemeral."
);
}
break;
default:
break;
}
}
//this function tells the bot to reply to an interaction so it doesn't seem like it fails (in case there is no onFail message).
if (onFail === undefined && args === "slash") {
onFail = "This command is disabled.";
await ctx.reply({ content: onFail, ephemeral: true });
}
//stop the command from running
return controller.stop();
});
}

View File

@@ -2,3 +2,4 @@ export * from './publish.js'
export * from './ownerOnly.js' export * from './ownerOnly.js'
export * from './srIzanOnly.js' export * from './srIzanOnly.js'
export * from './acceptingBirthday.js' export * from './acceptingBirthday.js'
export * from './disable.js'

View File

@@ -31,7 +31,7 @@ export default class Finder {
) {} ) {}
private async loadRecipes() { private async loadRecipes() {
const file = JSON.parse(await fs.readFile("./util/infinitecraft/recipes.json", "utf-8")) as ICFile const file = JSON.parse(await fs.readFile("./assets/icRecipes.json", "utf-8")) as ICFile
this.recipes = await decompressRecipes(file); this.recipes = await decompressRecipes(file);
this.items = new Set<string>(file.items); this.items = new Set<string>(file.items);
for (const recipe of this.recipes) { for (const recipe of this.recipes) {

View File

@@ -1,12 +1,11 @@
import { import {
Collection, Collection,
CommandInteraction,
GuildBasedChannel, GuildBasedChannel,
GuildMember, GuildMember,
Role, Role,
User, User,
} from 'discord.js'; } from 'discord.js';
import type { Snowflake } from 'discord.js'; import type { ChatInputCommandInteraction, Snowflake } from 'discord.js';
/** /**
* It resolves mentions from the content of a command * It resolves mentions from the content of a command
@@ -19,7 +18,7 @@ import type { Snowflake } from 'discord.js';
export class Resolver { export class Resolver {
public constructor( public constructor(
private readonly content: string, private readonly content: string,
private readonly interaction: CommandInteraction private readonly interaction: ChatInputCommandInteraction
) {} ) {}
readonly #regex = { readonly #regex = {

View File

@@ -1,6 +1,6 @@
import { ActionRow, ActionRowBuilder, AutocompleteInteraction, ButtonBuilder, ButtonStyle, EmbedBuilder } from "discord.js"; import { ActionRow, ActionRowBuilder, AutocompleteInteraction, ButtonBuilder, ButtonStyle, CacheType, CommandInteractionOptionResolver, CommandInteractionResolvedData, EmbedBuilder } from "discord.js";
import axios from "axios"; import axios from "axios";
import { Context, SlashOptions } from "@sern/handler"; import { Context } from "@sern/handler";
/** /**
Search Wikipedia for a given input string in the specified language using the Wikipedia API. Search Wikipedia for a given input string in the specified language using the Wikipedia API.
@@ -10,8 +10,7 @@ import { Context, SlashOptions } from "@sern/handler";
@param {AutocompleteInteraction} autocomplete - The autocomplete interaction object containing the input to search for. @param {AutocompleteInteraction} autocomplete - The autocomplete interaction object containing the input to search for.
@returns {Promise<SearchWikipediaObject[]>} - A promise that resolves with an array of search results. @returns {Promise<SearchWikipediaObject[]>} - A promise that resolves with an array of search results.
**/ **/
export async function searchWikipedia(lang: string, autocomplete: AutocompleteInteraction<CacheType>) {
export async function searchWikipedia(lang: string, autocomplete: AutocompleteInteraction) {
const input = autocomplete.options.getFocused() const input = autocomplete.options.getFocused()
if (!input) { if (!input) {
return [{ ns: 0, title: 'Empieza a escribir para buscar!', pageid: 0, size: 0, wordcount: 0, snippet: 0, timestamp: 0 }] as unknown as SearchWikipediaObject[] return [{ ns: 0, title: 'Empieza a escribir para buscar!', pageid: 0, size: 0, wordcount: 0, snippet: 0, timestamp: 0 }] as unknown as SearchWikipediaObject[]
@@ -20,7 +19,7 @@ export async function searchWikipedia(lang: string, autocomplete: AutocompleteIn
return request.data.query.search as SearchWikipediaObject[] return request.data.query.search as SearchWikipediaObject[]
} }
export async function getWikipedia(lang: string, ctx: Context, options: SlashOptions) { export async function getWikipedia(lang: string, ctx: Context, options: CommandInteractionOptionResolver<CacheType>) {
const pageid = options.getString((lang === 'es') ? 'busqueda' : 'search', true) const pageid = options.getString((lang === 'es') ? 'busqueda' : 'search', true)
if (Number.isNaN(Number(pageid))) return ctx.reply({ content: 'Elige en el autocompletado el artículo.', ephemeral: true }) if (Number.isNaN(Number(pageid))) return ctx.reply({ content: 'Elige en el autocompletado el artículo.', ephemeral: true })
const request = await axios.get(`https://${lang}.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&explaintext&pageids=${pageid}&format=json`) const request = await axios.get(`https://${lang}.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&explaintext&pageids=${pageid}&format=json`)

Some files were not shown because too many files have changed in this diff Show More