Necord
Necord Discord botlarini yaratishni soddalashtiradigan qulay modul bo'lib, NestJS ilovangizga bevosita integratsiya qilish imkonini beradi.
Necord Discord botlarini yaratishni soddalashtiradigan qulay modul bo'lib, NestJS ilovangizga bevosita integratsiya qilish imkonini beradi.
Necord uchinchi tomon paketi bo'lib, NestJS core jamoasi tomonidan rasmiy qo'llab-quvvatlanmaydi. Muammo uchratsa, iltimos, rasmiy repoda xabar bering.
O'rnatish
Boshlash uchun Necord ni va uning qaramligi Discord.js ni o'rnating.
1$ npm install necord discord.jsFoydalanish
Necord dan loyihangizda foydalanish uchun NecordModule ni import qiling va kerakli parametrlarga sozlang.
1import { Module } from '@nestjs/common';
2import { NecordModule } from 'necord';
3import { IntentsBitField } from 'discord.js';
4import { AppService } from './app.service';
5
6@Module({
7 imports: [
8 NecordModule.forRoot({
9 token: process.env.DISCORD_TOKEN,
10 intents: [IntentsBitField.Flags.Guilds],
11 development: [process.env.DISCORD_DEVELOPMENT_GUILD_ID],
12 }),
13 ],
14 providers: [AppService],
15})
16export class AppModule {}Mavjud intentlar to'liq ro'yxatini bu yerda topishingiz mumkin.
Shu sozlama bilan providerlaringizga AppService ni inject qilib, commandlar, eventlar va boshqalarni oson ro'yxatdan o'tkazishingiz mumkin.
1import { Injectable, Logger } from '@nestjs/common';
2import { Context, On, Once, ContextOf } from 'necord';
3import { Client } from 'discord.js';
4
5@Injectable()
6export class AppService {
7 private readonly logger = new Logger(AppService.name);
8
9 @Once('ready')
10 public onReady(@Context() [client]: ContextOf<'ready'>) {
11 this.logger.log(`Bot logged in as ${client.user.username}`);
12 }
13
14 @On('warn')
15 public onWarn(@Context() [message]: ContextOf<'warn'>) {
16 this.logger.warn(message);
17 }
18}Kontekstni tushunish
Yuqoridagi misollarda @Context dekoratorini payqagandirsiz. Bu dekorator metodga event kontekstini inject qiladi, shuning uchun eventga xos ma'lumotlarga kira olasiz. Turli event turlari mavjud bo'lganidan, kontekst turi ContextOf<type: string> orqali aniqlanadi. @Context() dekoratori yordamida kontekst o'zgaruvchilariga oson kirish mumkin, u o'zgaruvchini eventga tegishli argumentlar massiviga to'ldiradi.
Matn commandlari
Matn commandlari xabar tarkibiga tayanadi, bu esa tekshirilgan botlar va 100 dan ortiq serverga ega ilovalar uchun bekor qilinadi. Demak, bot xabar tarkibiga kira olmasa, matn commandlari ishlamaydi. Bu o'zgarish haqida ko'proq bu yerda o'qing.
Quyida @TextCommand dekoratori yordamida xabarlar uchun oddiy command handler yaratish ko'rsatilgan.
1import { Injectable } from '@nestjs/common';
2import { Context, TextCommand, TextCommandContext, Arguments } from 'necord';
3
4@Injectable()
5export class AppCommands {
6 @TextCommand({
7 name: 'ping',
8 description: 'Responds with pong!',
9 })
10 public onPing(
11 @Context() [message]: TextCommandContext,
12 @Arguments() args: string[],
13 ) {
14 return message.reply('pong!');
15 }
16}Ilova commandlari
Ilova commandlari foydalanuvchilarga Discord klienti ichida ilovangiz bilan o'zaro ishlashning native usulini beradi. Ularni turli interfeyslar orqali chaqirish mumkin bo'lgan uch tur mavjud: chat input, message kontekst menyusi (xabarga o'ng tugma), va user kontekst menyusi (foydalanuvchiga o'ng tugma).
Slash commandlar
Slash commandlar foydalanuvchilar bilan tuzilgan tarzda muloqot qilishning ajoyib usuli. Ular aniq argument va parametrlarga ega commandlar yaratishga imkon beradi va foydalanuvchi tajribasini sezilarli darajada yaxshilaydi.
Necord bilan slash command aniqlash uchun SlashCommand dekoratoridan foydalanishingiz mumkin.
1import { Injectable } from '@nestjs/common';
2import { Context, SlashCommand, SlashCommandContext } from 'necord';
3
4@Injectable()
5export class AppCommands {
6 @SlashCommand({
7 name: 'ping',
8 description: 'Responds with pong!',
9 })
10 public async onPing(@Context() [interaction]: SlashCommandContext) {
11 return interaction.reply({ content: 'Pong!' });
12 }
13}Bot klientingiz login qilganda barcha aniqlangan commandlarni avtomatik ro'yxatdan o'tkazadi. Global commandlar bir soatgacha keshda qolishini unutmang. Global kesh bilan bog'liq muammolardan qochish uchun Necord modulidagi development argumentidan foydalaning, u command ko'rinishini bitta guild bilan cheklaydi.
Parametrlar
Slash commandlar uchun parametrlarni option dekoratorlari yordamida belgilashingiz mumkin. Buning uchun TextDto klassini yarataylik:
1import { StringOption } from 'necord';
2
3export class TextDto {
4 @StringOption({
5 name: 'text',
6 description: 'Input your text here',
7 required: true,
8 })
9 text: string;
10}Keyin bu DTO ni AppCommands klassida ishlatishingiz mumkin:
1import { Injectable } from '@nestjs/common';
2import { Context, SlashCommand, Options, SlashCommandContext } from 'necord';
3import { TextDto } from './length.dto';
4
5@Injectable()
6export class AppCommands {
7 @SlashCommand({
8 name: 'length',
9 description: 'Calculate the length of your text',
10 })
11 public async onLength(
12 @Context() [interaction]: SlashCommandContext,
13 @Options() { text }: TextDto,
14 ) {
15 return interaction.reply({
16 content: `The length of your text is: ${text.length}`,
17 });
18 }
19}O'rnatilgan option dekoratorlarining to'liq ro'yxati uchun shu hujjatga qarang.
Avto-to'ldirish
Slash commandlar uchun avto-to'ldirish funksiyasini joriy qilish uchun interceptor yaratishingiz kerak bo'ladi. Bu interceptor foydalanuvchi avto-to'ldirish maydonida yozayotganda so'rovlarni ko'rib chiqadi.
1import { Injectable } from '@nestjs/common';
2import { AutocompleteInteraction } from 'discord.js';
3import { AutocompleteInterceptor } from 'necord';
4
5@Injectable()
6class CatsAutocompleteInterceptor extends AutocompleteInterceptor {
7 public transformOptions(interaction: AutocompleteInteraction) {
8 const focused = interaction.options.getFocused(true);
9 let choices: string[];
10
11 if (focused.name === 'cat') {
12 choices = ['Siamese', 'Persian', 'Maine Coon'];
13 }
14
15 return interaction.respond(
16 choices
17 .filter((choice) => choice.startsWith(focused.value.toString()))
18 .map((choice) => ({ name: choice, value: choice })),
19 );
20 }
21}Parametrlar klassini autocomplete: true bilan belgilashingiz ham kerak bo'ladi:
1import { StringOption } from 'necord';
2
3export class CatDto {
4 @StringOption({
5 name: 'cat',
6 description: 'Choose a cat breed',
7 autocomplete: true,
8 required: true,
9 })
10 cat: string;
11}Va nihoyat, interceptorni slash commandga qo'llang:
1import { Injectable, UseInterceptors } from '@nestjs/common';
2import { Context, SlashCommand, Options, SlashCommandContext } from 'necord';
3import { CatDto } from '/cat.dto';
4import { CatsAutocompleteInterceptor } from './cats-autocomplete.interceptor';
5
6@Injectable()
7export class CatsCommands {
8 @UseInterceptors(CatsAutocompleteInterceptor)
9 @SlashCommand({
10 name: 'cat',
11 description: 'Retrieve information about a specific cat breed',
12 })
13 public async onSearch(
14 @Context() [interaction]: SlashCommandContext,
15 @Options() { cat }: CatDto,
16 ) {
17 return interaction.reply({
18 content: `I found information on the breed of ${cat} cat!`,
19 });
20 }
21}User kontekst menyusi
User commandlari foydalanuvchiga o'ng tugma (yoki bosish) qilganda ochiladigan kontekst menyusida ko'rinadi. Bu commandlar foydalanuvchilarga bevosita yo'naltirilgan tezkor harakatlarni taqdim etadi.
1import { Injectable } from '@nestjs/common';
2import { Context, UserCommand, UserCommandContext, TargetUser } from 'necord';
3import { User } from 'discord.js';
4
5@Injectable()
6export class AppCommands {
7 @UserCommand({ name: 'Get avatar' })
8 public async getUserAvatar(
9 @Context() [interaction]: UserCommandContext,
10 @TargetUser() user: User,
11 ) {
12 return interaction.reply({
13 embeds: [
14 new MessageEmbed()
15 .setTitle(`Avatar of ${user.username}`)
16 .setImage(user.displayAvatarURL({ size: 4096, dynamic: true })),
17 ],
18 });
19 }
20}Xabar kontekst menyusi
Message commandlari xabarga o'ng tugma bosilganda kontekst menyusida paydo bo'ladi va shu xabarga tegishli tezkor harakatlarni bajarishga imkon beradi.
1import { Injectable } from '@nestjs/common';
2import { Context, MessageCommand, MessageCommandContext, TargetMessage } from 'necord';
3import { Message } from 'discord.js';
4
5@Injectable()
6export class AppCommands {
7 @MessageCommand({ name: 'Copy Message' })
8 public async copyMessage(
9 @Context() [interaction]: MessageCommandContext,
10 @TargetMessage() message: Message,
11 ) {
12 return interaction.reply({ content: message.content });
13 }
14}Tugmalar
Buttons xabarlarga qo'shilishi mumkin bo'lgan interaktiv elementlardir. Ularni bosganda ilovangizga interaction yuboriladi.
1import { Injectable } from '@nestjs/common';
2import { Context, Button, ButtonContext } from 'necord';
3
4@Injectable()
5export class AppComponents {
6 @Button('BUTTON')
7 public onButtonClick(@Context() [interaction]: ButtonContext) {
8 return interaction.reply({ content: 'Button clicked!' });
9 }
10}Select menyular
Select menus xabarlarda paydo bo'ladigan boshqa turdagi interaktiv komponent. U foydalanuvchilarga dropdownga o'xshash UI orqali variantlarni tanlash imkonini beradi.
1import { Injectable } from '@nestjs/common';
2import { Context, StringSelect, StringSelectContext, SelectedStrings } from 'necord';
3
4@Injectable()
5export class AppComponents {
6 @StringSelect('SELECT_MENU')
7 public onSelectMenu(
8 @Context() [interaction]: StringSelectContext,
9 @SelectedStrings() values: string[],
10 ) {
11 return interaction.reply({ content: `You selected: ${values.join(', ')}` });
12 }
13}O'rnatilgan select menyu komponentlarining to'liq ro'yxati uchun shu havolaga tashrif buyuring.
Modallar
Modallar foydalanuvchilarga formatlangan ma'lumot yuborishga imkon beradigan pop-up formalar. Necord yordamida modallarni yaratish va qayta ishlash usuli:
1import { Injectable } from '@nestjs/common';
2import { Context, Modal, ModalContext } from 'necord';
3
4@Injectable()
5export class AppModals {
6 @Modal('pizza')
7 public onModal(@Context() [interaction]: ModalContext) {
8 return interaction.reply({
9 content: `Your fav pizza : ${interaction.fields.getTextInputValue('pizza')}`
10 });
11 }
12}Qo'shimcha ma'lumot
Qo'shimcha ma'lumot uchun Necord saytiga tashrif buyuring.