Skip to main content

Commandes slash

Les commandes slash constituent la nouvelle façon passionnante de créer des bots sur Discord et d'interagir avec eux. Avec les commandes slash, il vous suffit de taper / et vous êtes prêt à utiliser votre bot favori. Vous pouvez facilement voir toutes les commandes dont dispose un bot, et la validation ainsi que la gestion des erreurs vous aident à saisir la commande correctement du premier coup.

Commandes slash

Commandes globales

astuce

Les commandes globales sont mises en cache pendant une heure. Les nouvelles commandes globales se propagent lentement sur tous les serveurs et leur mise à jour n'est garantie qu'au bout d'une heure. Les commandes de serveur se mettent à jour instantanément. C'est pourquoi nous vous recommandons d'utiliser des commandes basées sur le serveur pendant le développement et de les publier en tant que commandes globales lorsqu'elles sont prêtes pour une utilisation publique.

En savoir plus sur la configuration du mode développement

Créez le fichier app.commands.ts et ajoutez une méthode avec le décorateur SlashCommand.

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

@Injectable()
export class AppCommands {
@SlashCommand({
name: 'ping',
description: 'Ping-Pong Command'
})
public async onPing(@Context() [interaction]: SlashCommandContext) {
return interaction.reply({ content: 'Pong!' });
}
}

Commandes de serveur

Si vous souhaitez avoir des commandes spécifiques à un serveur, utilisez la propriété guilds sur le décorateur SlashCommand

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

@Injectable()
export class AppCommands {
@SlashCommand({
name: 'ping',
description: 'Ping-Pong Command',
guilds: [process.env.DEV_GUILD]
})
public async onPing(@Context() [interaction]: SlashCommandContext) {
return interaction.reply({ content: 'Pong!' });
}
}

Vous pouvez utiliser le décorateur à la fois sur la méthode et sur la classe.

Options

Utilisez le décorateur d'option pour définir un paramètre dans une commande slash, créons la classe LengthDto :

length.dto.ts
import { StringOption } from 'necord';

export class TextDto {
@StringOption({
name: 'text',
description: 'Your text',
required: true
})
text: string;
}

Elle ne possède qu'une seule propriété de base. Nous pouvons ensuite utiliser le DTO nouvellement créé dans AppCommands :

app.commands.ts
import { Injectable } from '@nestjs/common';
import { Context, SlashCommand, Options, SlashCommandContext } from 'necord';
import { TextDto } from './length.dto';

@Injectable()
export class AppCommands {
@SlashCommand({
name: 'length',
description: 'Get length of text'
})
public async onLength(@Context() [interaction]: SlashCommandContext, @Options() { text }: TextDto) {
return interaction.reply({content: `Length of your text ${text.length}`});
}
}

Liste de tous les décorateurs d'option intégrés :

DécorateurTypeDescription
StringOptionstringUne option de type chaîne de caractères
NumberOptionnumberUne option de type nombre
IntegerOptionnumberUne option de type entier
BooleanOptionbooleanUne option de type booléen
UserOptionUserUne option de type utilisateur
MemberOptionGuildMemberUne option de type membre
ChannelOptionGuildChannelA channel option
RoleOptionRoleA role option
MentionableOptionGuildMember | Role | UserA mentionable option
AttachmentOptionAttachmentAn attachment option

Autocomplete

To add autocomplete to your Slashcommand you will need a interceptor first. This class will intercept all requests from the user after typing in the autocomplete option field

anime.interceptor.ts
import { Injectable } from '@nestjs/common';
import { AutocompleteInteraction } from 'discord.js';
import { AutocompleteInterceptor } from 'necord';

@Injectable()
export class AnimeAutocompleteInterceptor extends AutocompleteInterceptor {
public transformOptions(interaction: AutocompleteInteraction) {
const focused = interaction.options.getFocused(true);
let choices: string[];

if (focused.name === 'anime') {
choices = ['Hunter x Hunter', 'Naruto', 'One Piece'];
}

return interaction.respond(
choices
.filter(choice => choice.startsWith(focused.value.toString()))
.map(choice => ({ name: choice, value: choice }))
);
}
}

You'll then have to add autocomplete: true to your options class:

anime.dto.ts
import { StringOption } from 'necord';

export class AnimeDto {
@StringOption({
name: 'anime',
description: 'The anime to look up',
autocomplete: true,
required: true
})
anime: string;
}

And last but not least, apply the interceptor to your slash command

anime-commands.service.ts
import { Injectable, UseInterceptors } from '@nestjs/common';
import { Context, SlashCommand, Options, SlashCommandContext } from 'necord';
import { AnimeDto } from '/anime.dto';
import { AnimeAutocompleteInterceptor } from './anime.interceptor';

@Injectable()
export class AnimeCommands {
@UseInterceptors(AnimeAutocompleteInterceptor)
@SlashCommand({
name: 'anime',
description: 'Lookup information about an anime'
})
public async onSearch(@Context() [interaction]: SlashCommandContext, @Options() { anime }: AnimeDto) {
return interaction.reply({content: `I found the anime ${anime}`});
}
}

Groups

TIP

For those developers looking to make more organized and complex groups of commands, look no further than subgroups and groups.

Use SlashGroup decorators on class-level (Group) and method-level (SubGroup):

utils-commands.service.ts
import { createCommandGroupDecorator, Subcommand } from 'necord';

export const UtilsCommandDecorator = createCommandGroupDecorator({
name: 'utils',
description: 'Utils group',
});

@UtilsCommandDecorator()
export class UtilsCommands {
@Subcommand({
name: 'ping',
description: 'Ping-pong command'
})
public async onPing(...) {
...
}
}

@UtilsCommandDecorator({
name: 'string',
descriptionn: 'String utility commands'
})
export class UtilsStringCommands {
@Subcommand({
name: 'length',
description: 'String length command'
})
public async onLength(...) {
...
}
}


After the registration commands, the bot will process /utils ping and /utils string length commands, like here:

Commands

You can view a working example here.