Перейти к содержанию

Начало работы

В этой статье вы узнаете об основах necord и о том, как он интегрируется с NestJS!

совет

Многие концепции, представленные в necord, разработаны для использования так же, как и другие компоненты в NestJS. Мы рекомендуем вам ознакомиться с документацией NestJS, особенно с разделом введение, перед тем как начать.

Первым шагом является установка necord и его зависимости, Discord.js

npm install necord discord.js
совет

Для работы с Necord и Discord.js вам необходимо установить Node.js v18.0.0 или новее.

Настройка модуля

Necord - это такой же модуль, как и любые другие, и может быть импортирован как таковой в ваше приложение Nest.

Модули NestJS

Не знаете, что такое модули? Узнайте о них в документации NestJS!

discord.module.ts
import { Module } from '@nestjs/common';
import { AppService } from './app.service';
import { IntentsBitField } from 'discord.js';

@Module({
imports: [
NecordModule.forRoot({
token: process.env.DISCORD_TOKEN,
intents: [IntentsBitField.Flags.Guilds],
development: [process.env.DISCORD_DEVELOPMENT_GUILD_ID]
})
],
providers: [AppService]
})
export class DiscordModule {}
инфо

Make sure to setup the correct intents required by your application!

The module arguments are an extension of discord.js ClientOptions, in addition to 3 necord options: token, prefix and development.

export interface NecordModuleOptions extends DiscordClientOptions {
token: string;
prefix?: string | (message: Message) => string | Promise<string>;
development?: Snowflake[] | false;
skipRegistration?: boolean;
}
PropertyTypeDescription
tokenstringYour Discord token
prefixstring or (message: Message) => stringThe prefix for your bot
developmentSnowflake[] or falseThe development guilds for your bot
skipRegistrationbooleanSkip automatic registration of application commands
Warning

If you have commands using the guilds property, the global development argument will not overwrite it.

Slash Commands

The best way to interact with your users is to use Slash commands! Slash commands allow you to create commands with precise arguments and choices, giving users the best experience.

To create a command with Necord, you can use the SlashCommand decorator.

app.service.ts
import { Injectable } from '@nestjs/common';
import { Context, SlashCommand, SlashCommandContext } from 'necord';

@Injectable()
export class AppService {
@SlashCommand({
name: 'ping',
description: 'Ping command!'
})
public async onPing(@Context() [interaction]: SlashCommandContext) {
return interaction.reply({ content: 'Pong!' });
}
}
совет

When the client logs in, it will automatically register all of the commands. Global commands are cached for up to an hour, therefore to avoid the global commands cache, you should use the development argument on the Necord module. This will restrict the command to a single guild, preventing it from getting caught by the cache.

Running the application

You can run the following command at your OS command prompt to start the application listening Discord API events:

$ npm run start

You can view a working example here.