1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

discordの音声BOT作りました(再度掲載)

Last updated at Posted at 2023-05-17

こんにちはななしひろゆきです
今回はdiscordBOTを作りました
この記事は再掲載です

まずindex.jx

index.js
const { Client, Collection, GatewayIntentBits, Partials ,MessageEmbed} = require('discord.js');
const { createAudioResource, createAudioPlayer, joinVoiceChannel } = require('@discordjs/voice');
const fs = require('fs');
const { LISTENER } = require('./config.json');
const Database = require('better-sqlite3');
const db = new Database('inm_discord_bot', { verbose: console.log });
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildBans,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildWebhooks,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMessageTyping,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.DirectMessageTyping,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildScheduledEvents,
],
partials: [
Partials.User,
Partials.Channel,
Partials.GuildMember,
Partials.Message,
Partials.Reaction,
Partials.GuildScheduledEvent,
Partials.ThreadMember,
],
});

client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
  const command = require(`./commands/${file}`);
  client.commands.set(command.data.name, command);
}

client.once('ready', () => {
  console.log('起動完了');
});

client.on('interactionCreate', async interaction => {
  if (!interaction.isCommand()) {
  return;
  }
  const { commandName } = interaction;
  const command = client.commands.get(commandName);
  console.log(command);
  if (!command) {
    return;
  }
  try {
    await command.execute(interaction);
  } catch (error) {
    console.error(error);
    interaction.reply('There was an error trying to execute that command!');
  }
});

client.on('messageCreate',async message => {
  if (!message.author.bot && message.content.length > 0) {
    console.log(message.content);
    try {
      const voiceChannel = message.member.voice.channel;
      var filePath = '';
      var file = ('%'+message.content+'%');
      var check =  db.prepare('SELECT voice_file_name.name,voice_select_name.* FROM voice_select_name INNER JOIN voice_file_name ON voice_file_name.id = voice_select_name.voice_file_name WHERE voice_select_name.name LIKE ?').get(file);
      if(!check){
      }else{
        console.log(check.name);
        var select_voice = db.prepare(' SELECT * FROM voice_file_name WHERE id = ?').get(check.voice_file_name);
        filePath = './voice_file/'+select_voice.name;
        console.log(filePath);
      }
      if (!fs.existsSync(filePath)) {
        return await message.reply('指定されたWAVファイルが見つかりません。'+filename);
      }
      // ボイスコネクションを作成し、ボイスチャンネルに接続します。
      const connection = joinVoiceChannel({
        channelId: voiceChannel.id,
        guildId: voiceChannel.guild.id,
        adapterCreator: voiceChannel.guild.voiceAdapterCreator,
      });
      
      // 再生するオーディオリソースを作成します。
      const resource = createAudioResource(filePath);

      // オーディオプレーヤーを作成し、オーディオリソースを再生します。
      const player = createAudioPlayer();
      connection.subscribe(player);
      player.play(resource);
    
    } catch (error) {
      console.error(error);
      message.reply('There was an error trying to execute that command!');
    }
  }
});

client.login(LISTENER.TOKEN);

続いてdeploy_commands.js

deploy_commands.js
const { SlashCommandBuilder } = require('@discordjs/builders'); //SlashCommandBuilderを読み込む
const fs = require('fs');
const { REST } = require('@discordjs/rest'); //RESTを読み込む
const { Routes } = require('discord-api-types/v9'); //Routesを読み込む
const { LISTENER,GUILD_ID } = require('./config.json');
const client_id  = LISTENER.CLIENT_ID //クライアントIDをclient_idに代入
const guild_id = GUILD_ID //サーバーIDをguild_idに代入
const token = LISTENER.TOKEN //トークン
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
const test = [].map(command => command.toJSON());
  for (const file of commandFiles) {
       const commacommandBOTnd = require(`./commands/${file}`);
       test.push(new SlashCommandBuilder().setName(commacommandBOTnd.data.name).setDescription(commacommandBOTnd.data.description));
  }
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(client_id, guild_id), { body: test }) 
    .then(() => console.log('Successfully registered application commands.'))
    .catch(console.error); //指定したサーバーにコマンドを登録・更新

続いてvoicechat.js

voicechat.js
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('参加しました!');
	},
};

続いてcomandsファイルの中にあるコマンドを実行した際に起動するコード

join.js
const { SlashCommandBuilder } = require('@discordjs/builders');

// 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('おまたせ');
	},
};
disconnect.js
const { SlashCommandBuilder } = require('@discordjs/builders');
const { LISTENER } = require('../config.json');
const { joinVoiceChannel, getVoiceConnection } = require('@discordjs/voice');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('disconnect')
    .setDescription('ボイスチャンネルから切断します。'),

  async execute(interaction) {
    // 接続済みのボイスコネクションを取得します。
    const connection = getVoiceConnection(interaction.guildId);
    // もし接続が存在しなければ、エラーを返します。
    if (!connection) {
      return await interaction.reply('ボイスチャンネルに接続していません。');
    }
    // ボイスチャンネルから切断します。
    connection.destroy();

    // 成功メッセージを返します。
    return await interaction.reply('ボイスチャンネルから切断しました。');
  },
};

続いて
データベースに値を入れる為のjs

database.js
console.log('helloworld');
const Database = require('better-sqlite3');
const fs = require('fs');
const db = new Database('inm_discord_bot', { verbose: console.log });
const commandFiles = fs.readdirSync('./voice_file').filter(file => file.endsWith('.wav'));
console.log(commandFiles);
var stmt = db.prepare('INSERT INTO voice_file_name (name) VALUES (?);');
for (const file of commandFiles) {
    var check =  db.prepare('SELECT * FROM voice_file_name WHERE name = ?').get(file);
    if(!check){
        stmt.run(file);
    }
}
const row = db.prepare('SELECT * FROM voice_file_name ').get();
console.log(row);

database.jsにてデータを入れたのちdeploy.jsを起動する事で呼び出すようにしてあります

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?