Saltearse al contenido

Configurando Seyfert

Configuración de TypeScript

Para que Seyfert funcione correctamente debes actualizar tu archivo tsconfig.json y añadir emitDecoratorMetadata y experimentalDecorators para poder utilizar decoradores:

tsconfig.json
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
}
}


Selección del tipo de bot

Seyfert ofrece soporte para dos tipos de aplicaciones que interactúan con la API de Discord: una basada en la gateway (websocket) y otra basada en el sistema de interacción HTTP.

Cada tipo tiene un propósito distinto, y es crucial comprender sus diferencias para elegir el que mejor se adapte a tus necesidades. Si no estás seguro de qué tipo de bot elegir, te recomendamos usar la opción Gateway.

  • El cliente Gateway maneja todos los eventos emitidos por Discord, como messageCreate, interactionCreate, guildCreate, ready, entre otros.
  • Los eventos disponibles dependen de los intents configurados en el cliente.

Configuración

Una vez modificado el tsconfig.json para soportar decoradores, aún nos quedan algunos pasos antes de poder ejecutar la aplicación. Seyfert se ajusta para cargar tus comandos, eventos, componentes e idioma de forma automática.

Para ello es necesario crear un archivo llamado seyfert.config.mjs en la carpeta raíz de tu proyecto y añadir la configuración según el tipo de bot que elegiste:

seyfert.config.mjs
import {
const config: {
bot(data: RuntimeConfig): InternalRuntimeConfig;
http(data: RuntimeConfigHTTP): InternalRuntimeConfigHTTP;
}
config
} from "seyfert";
export default
const config: {
bot(data: RuntimeConfig): InternalRuntimeConfig;
http(data: RuntimeConfigHTTP): InternalRuntimeConfigHTTP;
}
config
.
function bot(data: RuntimeConfig): InternalRuntimeConfig

Configurations for the bot.

@paramdata - The runtime configuration data for gateway connections.

@returnsThe internal runtime configuration.

bot
({
token: string
token
:
var process: NodeJS.Process
process
.
NodeJS.Process.env: NodeJS.ProcessEnv

The process.env property returns an object containing the user environment. See environ(7).

An example of this object looks like:

{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}

It is possible to modify this object, but such modifications will not be reflected outside the Node.js process, or (unless explicitly requested) to other Worker threads. In other words, the following example would not work:

Terminal window
node -e 'process.env.foo = "bar"' && echo $foo

While the following will:

import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);

Assigning a property on process.env will implicitly convert the value to a string. This behavior is deprecated. Future versions of Node.js may throw an error when the value is not a string, number, or boolean.

import { env } from 'node:process';
env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'

Use delete to delete a property from process.env.

import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined

On Windows operating systems, environment variables are case-insensitive.

import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1

Unless explicitly specified when creating a Worker instance, each Worker thread has its own copy of process.env, based on its parent thread's process.env, or whatever was specified as the env option to the Worker constructor. Changes to process.env will not be visible across Worker threads, and only the main thread can make changes that are visible to the operating system or to native add-ons. On Windows, a copy of process.env on a Worker instance operates in a case-sensitive manner unlike the main thread.

@sincev0.1.27

env
.
string | undefined
BOT_TOKEN
?? "",
locations: RCLocations
locations
: {
RCLocations.base: string
base
: "dist", // reemplazar por "src" en caso de usar bun
RCLocations.commands?: string
commands
: "commands"
},
intents?: number | IntentStrings | number[]
intents
: ["Guilds"],
// Esta configuración es opcional, por si desea recibir las interacciones por HTTP
// Así se puede usar tanto la gateway como el HTTP webhook
publicKey?: string
publicKey
: "...", // reemplazar por tu clave pública
port?: number
port
: 4444, // reemplazar por el puerto de tu aplicación
});

Esto no es todo, también necesitas crear un archivo principal llamado index.ts dentro de la carpeta src (especificada como base en la configuración) y empezar a usar

src/index.ts
import {
class Client<Ready extends boolean = boolean>
Client
} from "seyfert";
const
const client: Client<boolean>
client
= new
new Client<boolean>(options?: ClientOptions): Client<boolean>
Client
();
// Esto iniciará la conexión con la gateway de Discord y cargará comandos, eventos, componentes e idioma (i18n)
const client: Client<boolean>
client
.
Client<boolean>.start(options?: Omit<DeepPartial<StartOptions>, "httpConnection">, execute?: boolean): Promise<void>
start
();

Además de lo anterior, debes configurar los tipos correspondientes según el cliente que uses:

import type {
type ParseClient<T extends BaseClient> = T
ParseClient
,
class Client<Ready extends boolean = boolean>
Client
,
class HttpClient
HttpClient
,
class WorkerClient<Ready extends boolean = boolean>
WorkerClient
} from 'seyfert';
declare module 'seyfert' {
interface
interface UsingClient
UsingClient
extends
type ParseClient<T extends BaseClient> = T
ParseClient
<
class Client<Ready extends boolean = boolean>
Client
<true>> { }
interface
interface UsingClient
UsingClient
extends
type ParseClient<T extends BaseClient> = T
ParseClient
<
class HttpClient
HttpClient
> { }
interface
interface UsingClient
UsingClient
extends
type ParseClient<T extends BaseClient> = T
ParseClient
<
class WorkerClient<Ready extends boolean = boolean>
WorkerClient
<true>> { }
}

Para más información sobre cómo declarar los tipos y qué puedes hacer con ellos, visita extendiendo declare module.

Una vez completado los pasos, la estructura de su proyecto debe tener este aspecto:

  • Directorysrc
    • Directorycommands/
    • index.ts
  • package.json
  • seyfert.config.mjs
  • tsconfig.json
  • .env