LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

Discord.js 覚え書き

Last updated at Posted at 2023-12-12

この記事を読む前に......

執筆時間がなかったため、初歩の初歩だけ書きました。。。

はじめに

Discord.jsを使ったBot開発について学んだことを書き留めておく、自分用の覚え書きです。
なお、環境構築については省略します。

実行環境

名称 バージョン
Replit -
Node.js 16.11.0
Discord.js 14.14.1

Discord.jsでBotを作る

導入

メインファイル

以下のコードをベースにします。

index.js
// 最低限必要なDiscord.jsのクラスを読み込む
const { Client, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

// 新たにクライアントのインスタンスを作成
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

// クライアントの準備ができ次第、以下を一度だけ実行
client.once(Events.ClientReady, readyClient => {
	console.log(`Ready! Logged in as ${readyClient.user.tag}`);
});

// クライアントのトークンでDiscordにログイン
client.login(token);

Botの起動

Replitの場合は、▶ボタンを押すだけで実行してくれます。
ターミナルで起動する場合は、以下を実行します。

node index.js

スラッシュコマンド

前提

スラッシュコマンド(以下「コマンド」という。)は、SlashCommandBuilderを使うと簡単に作ることができます。
スラッシュコマンドの定義には、最低でも名前と説明が必要です。ここで設定した名前は、そのままコマンド名になります。
コマンド名は1~32文字で設定し、大文字・スペース・-および_以外の記号・日本語を含めることはできません。

new SlashCommandBuilder()
    .setName('reply')
	.setDescription('「こんにちは!」と返します');

コマンドが実行されたときに応答するため、関数が必要になります。
実行されたコマンドに対して応答する、最も簡単な関数は以下の通りです。

async execute(interaction) {
	await interaction.reply('こんにちは!')
}

以上を組み合わせると、以下のようなファイルを作ることができます。

reply.js
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
	data: new SlashCommandBuilder()
		.setName('reply')
		.setDescription('「こんにちは!」と返します'),
	async execute(interaction) {
		await interaction.reply('こんにちは!');
	},
};

おわりに

いずれ内容を追記すると思います。
恐らく別の記事で......

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