본문 바로가기

디스코드봇

[JS] 디스코드 노래 봇

반응형

디스코드에서 쓸만한 노래봇을 쓰려고 하는데 특정 기능을 사용하려 하니 유료결제가 필요하다길래 직접 만들어본다.

일단 node js 사용하였다. npm init 로 세팅하며 시작

 

필요한 모듈은 아래와 같다

npm install discord.js @discordjs/voice ytdl-core libsodium-wrappers

 

discord.js 는 discord에서 제공하는 기능을 사용하기위해

ytdl-core 는 youtube에서 url로 영상을 가져와 처리하기위해 사용한다

 

https://discord.com/developers/applications

 

Discord Developer Portal — API Docs for Bots and Developers

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

discord.com

에서 bot 세팅을 해주도록하자.

 

1. New Application 으로 새 프로젝트 생성

2. Bot -> Add Bot -> Yes do it 클릭 이후 Reset Token 버튼을 눌러 토큰 생

3. OAuth2 Url Generator -> bot 체크 권한은 사용자에 맞게 설정(그냥 administrator 줬다). 

4. 주소를 복사하여 웹에 복붙 -> 서버에 초대

 

이후 개발 소스는 여기저기 검색하고 gpt에 물어가면서 만들었다.

const { Client, GatewayIntentBits } = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus } = require('@discordjs/voice');
const ytdl = require('ytdl-core');
const { token } = require('./discordConfig.js');

const sodium = require('libsodium-wrappers'); // 추가된 부분

const client = new Client({
    intents: [
      GatewayIntentBits.Guilds,
      GatewayIntentBits.GuildVoiceStates,
      GatewayIntentBits.GuildMessages,
      GatewayIntentBits.MessageContent
    ]
  });

// 준비
client.on('ready', () => console.log(`${client.user.tag} 에 로그인됨`));

// 봇 명령어 구분 문자 
const prefix = '!아토믹'; 

let connection;
let voiceChannel;
let player;
client.on('messageCreate', async message => {
    if (message.author.bot) return;
    if (!message.content.startsWith(prefix)) return;
  
    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift();
    
    if (command === '붐') {

      const playUrl = 'https://www.youtube.com/watch?v=pZa6sTu8hLM&list=PLUQNSfSPIlNyUQi2tUdCBrtMl58wpWXfY&index=6';
      // if (!args[0]) {
      //   return message.reply('Please provide a YouTube link!');
      // }
  
      voiceChannel = message.member.voice.channel;
      if (!voiceChannel) {
        return message.reply('채널에 먼저 들가라');
      }
  
      const permissions = voiceChannel.permissionsFor(message.client.user);
      if (!permissions.has('CONNECT') || !permissions.has('SPEAK')) {
        return message.reply('권한내놔');
      }
  
      try {
        connection = joinVoiceChannel({
          channelId: voiceChannel.id,
          guildId: message.guild.id,
          adapterCreator: message.guild.voiceAdapterCreator,
        });
  
        //const stream = ytdl(args[0], { filter: 'audioonly' });
        const stream = ytdl(playUrl, {
           filter: 'audioonly',
           fmt: "mp3",
           highWaterMark: 1 << 62,
           liveBuffer: 1 << 62,
           dlChunkSize: 0, //disabling chunking is recommended in discord bot
           bitrate: 128,
           quality: "lowestaudio"
          });
        const resource = createAudioResource(stream);
        player = createAudioPlayer();
  
        player.play(resource);
        connection.subscribe(player);
  
        player.on(AudioPlayerStatus.Idle, () => {
          connection.destroy();
        });
  
        //message.reply(`Now playing: ${args[0]}`);
        message.reply(`Now playing: 아토믹 붐`);
      } catch (error) {
        console.error(error);
        message.reply('ㅅㅂ에러');
      }
    }
    else if (command === '중지') {
      if (player) {
          player.stop();
      }
      if (connection) {
          connection.destroy();
      }
    }
  });
  
  client.login(token);

 

토큰은 config 파일에 따로 빼놨다.

해당 파일을 Run 하면 디스코드에 봇이 온라인으로 되어있는걸 볼 수 있다.

지금은 !아토믹 붐 이라는 명령어로 특정 노래를 실행하도록, !아토믹 중지로 멈추는것 까지만 구현해두었다.

반응형

'디스코드봇' 카테고리의 다른 글

[JS] 디스코드 노래 봇 5  (0) 2024.08.24
[JS] 디스코드 노래 봇 4  (1) 2024.07.14
[JS] 디스코드 노래 봇 3  (0) 2024.06.30
[JS] 디스코드 노래 봇 2  (1) 2024.06.16