LoginSignup
5
2

More than 1 year has passed since last update.

【Discord.js V14】Discord BOTにスラッシュコマンドを実装してみる

Last updated at Posted at 2023-01-29

皆さん初めまして。Morichanと申します。
下記の※の記述を理解したうえで、記事を読んでください。

※DiscordBot開発初心者の書いた記事です。
(また、プログラミング自体、2年ほどのブランクあり)

環境構築からBOTを動かすまでの流れに関しては、別の記事にまとめてあります。

関連記事:

目次

  1. 開発環境
  2. スラッシュコマンドを実装してみる
  3. 関連記事

開発環境

OS (Windows11)
discord.js (14.7.1)
node.js (18.13.0)
npm (8.19.3)

スラッシュコマンドを実装してみる

まずは、公式ガイドに則って、/pingと送ったら、Pong!とBOTが返信するコマンドを実装してみます。

  • ルートディレクトリにcommandsというフォルダを作成。その中にping.jsというファイルを作成し、中身を記述。
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
	data: new SlashCommandBuilder()
        // コマンドの名前
		.setName('ping')
        // コマンドの説明文
		.setDescription('Pong!と返信。'),
	async execute(interaction) {
        // Pong!と返信
		await interaction.reply('Pong!');
	},
};
  • ボットが起動時に、コマンドファイルを読み込むための処理とコマンドを判別して実行するための処理をindex.jsに記述。
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { LISTENER } = require('./config.json');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.commands = new Collection();

// commandsフォルダから、.jsで終わるファイルのみを取得
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
	const filePath = path.join(commandsPath, file);
	const command = require(filePath);
	// 取得した.jsファイル内の情報から、コマンドと名前をListenner-botに対して設定
	if ('data' in command && 'execute' in command) {
		client1.commands.set(command.data.name, command);
	} else {
		console.log(`[WARNING]  ${filePath} のコマンドには、必要な "data" または "execute" プロパティがありません。`);
	}
}

// コマンドが送られてきた際の処理
client1.on(Events.InteractionCreate, async interaction => {
    // コマンドでなかった場合は処理せずさよなら。
	if (!interaction.isChatInputCommand()) return;

	const command = interaction.client.commands.get(interaction.commandName);

    // 一致するコマンドがなかった場合
	if (!command) {
		console.error(` ${interaction.commandName} というコマンドは存在しません。`);
		return;
	}

	try {
        // コマンドを実行
		await command.execute(interaction);
	} catch (error) {
		console.error(error);
		await interaction.reply({ content: 'コマンドを実行中にエラーが発生しました。', ephemeral: true });
	}
});

client.once(Events.ClientReady, c => {
    console.log(`Ready! Logged in as ${c.user.tag}`);
});

client.login(LISTENER.TOKEN);
  • 作成したスラッシュコマンドをBOTに登録。
    ルートディレクトリにdeploy-commands.jsを作成、中身を記述。
const { REST, Routes } = require('discord.js');
const { LISTENER, GUILD_ID } = require('./config.json');
const fs = require('node:fs');

const commands = [];
// Grab all the command files from the commands directory you created earlier
// commandsフォルダから、.jsで終わるファイルのみを取得
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
	const command = require(`./commands/${file}`);
	commands.push(command.data.toJSON());
}

// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(LISTENER.TOKEN);

// and deploy your commands!
(async () => {
	try {
		console.log(`Started refreshing ${commands.length} application (/) commands.`);

		// The put method is used to fully refresh all commands in the guild with the current set
		const data = await rest.put(
			Routes.applicationGuildCommands(LISTENER.CLIENT_ID, GUILD_ID),
			{ body: commands },
		);

		console.log(`Successfully reloaded ${data.length} application (/) commands.`);
	} catch (error) {
		// And of course, make sure you catch and log any errors!
		console.error(error);
	}
})();
  • VSCodeでターミナルを開き、node deploy-commands.jsを実行。
    image.png

  • BOTを招待したサーバーへ行き、チャット欄で/と入力すると、/pingが予測欄に出てくる。
    image.png

  • もう一度VSCordへ行き、ターミナルを開いて、node index.jsを実行。

  • Discordサーバーへ行き、チャット欄で/pingと入力、送信すると、Pong!と返ってくる。
    image.png

関連記事

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2