LoginSignup
0
1

More than 1 year has passed since last update.

【Discord.js V14】Discord BOTをVCに参加させてみる

Last updated at Posted at 2023-01-29

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

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

BOTにスラッシュコマンドを実装・登録するまでの流れに関しては、別の記事にまとめてあります。

関連記事:

目次

  1. 開発環境
  2. BOTをVCに参加させてみる
  3. スラッシュコマンドに引数を追加して、コマンド呼び出し時に参加するVCを指定できるようにする。
  4. 関連記事

開発環境

OS (Windows11)
discord.js (14.7.1)
node.js (18.13.0)
npm (8.19.3)
@discordjs/voice (^0.14.0)

BOTをVCに参加させてみる

  • VSCodeでターミナルを開き、必要なものをnpmを使用してインストール
npm i @discordjs/voice --save
  • 参加させたいVCを右クリック、IDをコピーし保管する。
    image.png

  • config.jsonのLISTENERの中に記述。

    "LISTENER": {
        "CLIENT_ID": "ここにBOTのCLIENT_IDを記述",
        "TOKEN": "ここにBOTのTOKENを記述",
        "VC_ID": "ここにBOTを参加させるVCのIDを記述"
    },
    "GUILD_ID": "ここにBOTを追加したサーバーのIDを記述"
const { SlashCommandBuilder } = require('discord.js');

// BOTをVCに参加させるために必要。
const { joinVoiceChannel } = require('@discordjs/voice');

const { LISTENER } = require('../config.json');

module.exports = {
	data: new SlashCommandBuilder()
        // コマンドの名前
		.setName('join')
        // コマンドの説明文
		.setDescription('VCに参加。'),
	async execute(interaction) {
        // VCに参加する処理
		const connection = joinVoiceChannel({
			guildId: interaction.guildId,
			channelId: LISTENER.VC_ID,
			adapterCreator: interaction.guild.voiceAdapterCreator,
		});
		await interaction.reply('参加しました!');
	},
};
  • VSCodeでターミナルを開き、node deploy-commands.jsnode index.jsを行い、Discordでコマンドを入力。
    image.png
    無事、BOTがVCに参加してくれました!

スラッシュコマンドに引数を追加して、コマンド呼び出し時に参加するVCを指定できるようにする。

const { SlashCommandBuilder, ChannelType } = require('discord.js');
const { joinVoiceChannel } = require('@discordjs/voice');
module.exports = {
	data: new SlashCommandBuilder()
        // コマンドの名前
		.setName('join')
        // コマンドの説明文
		.setDescription('VCに参加。')
		// コマンドのオプションを追加
        // 今回はチャンネルを選ばせたいので、addChannelOptionを使用
		.addChannelOption((option) =>
			option
                // optionの名前
				.setName('channel')
                // optionの説明
				.setDescription('The channel to join')
               // optionが必須かどうか
				.setRequired(true)
               // チャンネルのタイプをVCに指定
				.addChannelTypes(ChannelType.GuildVoice),
		),
	async execute(interaction) {
		const voiceChannel = interaction.options.getChannel('channel');
        // VCに参加する処理
		const connection = joinVoiceChannel({
			guildId: interaction.guildId,
			channelId: voiceChannel.id,
			adapterCreator: interaction.guild.voiceAdapterCreator,
		});
		await interaction.reply('参加しました!');
	},
};
  • 再びnode deploy-commands.jsnode index.jsを行い、Discordでコマンドを入力。
    VCを選択できるようになっています。
    image.png
    先ほどと変わらずにListener-botがVCに参加してくれました!
    image.png
    (VC2を選択)
    image.png

関連記事

0
1
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
0
1