Начало работы
В этой статье вы узнаете об основах necord и о том, как он интегрируется с NestJS!
Многие концепции, представленные в necord, разработаны для использования так же, как и другие компоненты в NestJS. Мы рекомендуем вам ознакомиться с документацией NestJS, особенно с разделом введение, перед тем как начать.
Первым шагом является установка necord и его зависимости, Discord.js
- npm
- Yarn
- pnpm
npm install necord discord.js
yarn add necord discord.js
pnpm add necord discord.js
Для работы с Necord и Discord.js вам необходимо установить Node.js v18.0.0 или новее.
Настройка модуля
Necord - это такой же модуль, как и любые другие, и может быть импортирован как таковой в ваше приложение Nest.
Не знаете, что такое модули? Узнайте о них в документации NestJS!
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 {}
Убедитесь, что настроены правильные привилегированные намерения, необходимые для вашего приложения!
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;
}
Property | Type | Description |
---|---|---|
token | string | Your Discord token |
prefix | string or (message: Message) => string | The prefix for your bot |
development | Snowflake[] or false | The development guilds for your bot |
skipRegistration | boolean | Skip automatic registration of application commands |
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.
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.
Запуск приложения
Вы можете выполнить следующую команду в командной строке вашей ОС, чтобы запустить приложение, прослушивающее события Discord API:
- npm
- Yarn
- pnpm
$ npm run start
$ yarn run start
$ pnpm run start
Рабочий пример можно посмотреть здесь.