discord.jsをTypeScriptでもっと楽しく書くためのライブラリ!
| package version | discord.js version |
|---|---|
| 0.5.0 | >=14.25.0 <15 |
| 0.4.0 | >=14.23.2 <14.25 |
| 0.3.0 | 14.24.0 |
| 0.2.1 | 14.23.2 |
SlashCommandのサンプル
import { wrapper } from 'sugar-djs';
import { SlashCommandBuilder } from 'discord.js';
import { isCachedInteraction } from './middlewares.ts';
export default wrapper
.setCommand(
// discord.jsのBuilderをそのまま使用
new SlashCommandBuilder()
.setName('ping')
.setDescription('Send "Pong!"')
)
.addMiddleware(isCachedInteraction) // キャッシュされたインタラクションのみ許可
.setProcess(({ interaction }) => {
// interaction: ChatInputCommandInteraction<"cached">;
interaction.reply('Pong!');
});Sugar-DJSを使うと、一部の型指定を省略したり、共通の処理を簡単に挿入できたりすることで、素早くボットを制作することができます。
Sugar-DJSは、渡されたBuilderからコマンドハンドラーのinteractionの型を推論します。
// 型を手動で指定する例
export const command = new SlashCommandBuilder().setName('ping')
export const execute = (interaction: ChatInputCommandInteraction) => {
interaction.reply('Pong!');
} // Sugar-DJSのコード
export default wrapper
.setCommand(
new SlashCommandBuilder().setName('ping')
)
.setProcess(({ interaction }) => { // 型が適切に推論されます
interaction.reply('Pong!');
});コマンドやコンポーネントの処理の前に、ミドルウェアを追加することができます。ミドルウェアは、Interactionを含むペイロードに対して処理を行い、追加のデータを返すことができます。また、ペイロードの形を絞る事もできます。
import { AnyInteraction, MiddlewarePayload } from 'sugar-djs';
export const isCachedInteraction = <T extends AnyInteraction, U>({
interaction,
...payload
}: MiddlewarePayload<T, U>) => {
if (!interaction.inCachedGuild()) {
interaction.reply("サーバー内で実行してください");
return; // voidを返した場合、次の処理は実行されません。
}
return { interaction, ...payload };
};コマンドやコンポーネントが格納されているディレクトリを指定して、WrapperCollectionのインスタンスを作成します。
// sugardjs.ts
import path from 'path';
import { WrapperCollection } from 'sugar-djs';
const commandsPath = path.join(__dirname, './commands');
const componentsPath = path.join(__dirname, './components');
export default new WrapperCollection({
paths: [commandsPath, componentsPath],
});手順1で作成したWrapperCollectionのinteractionCreateHandlerをdiscord.jsのInteractionCreateイベントのハンドラーとして渡します。
// index.ts
import wrappers from "./sugardjs";
...
client.on('interactionCreate', wrappers.interactionCreateHandler);
...手順1で作成したWrapperCollectionのtoJSONメソッドを活用すると、簡単にコマンドやコンポーネントを登録する処理が書けます。
// register.ts
import { REST, Routes } from 'discord.js';
import wrappers from './sugardjs';
const TOKEN = process.env.DISCORD_TOKEN;
const CLIENT_ID = process.env.DISCORD_CLIENT_ID;
const rest = new REST({ version: '10' }).setToken(TOKEN);
const commands = wrappers.toJSON(); // Discord API に渡せるJSONのリストを返します。
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands,
});MIT License (see LICENSE file).