음악봇을 만들기 위해 찾다 보면
결국 핵심은 어떻게 유튜브 영상을
리소스로 바꾸고 재생하느냐가 관건인데요.
대부분은 lavaLink 또는 스트리밍 라이브러리를
사용하시지만 직접 ytdl-core를 사용하면 다양한
기능을 사용할 수 있습니다.
이번 블로그에서는 어떻게 ytdl-core를 이용하여
디스코드 음악봇을 만들 수 있는가에 대해
설명하도록 하겠습니다!
필수 라이브러리 설치
npm install discord.js
npm install ytdl-core
npm install ffmpeg-static
npm install @discordjs/voice libsodium-wrappers
해당 블로그는 Deleting commands | discord.js Guide (discordjs.guide)를 참고하여 제작하였습니다.
1. connection & player 생성하기
connection 생성 ( 통화방에 연결 )
해당 연결은 아래와 같은 상태입니다.
1. 봇 뮤트 해제
2. 봇 말하기 적용
const { joinVoiceChannel } = require('@discordjs/voice');
/* interaction 기준 */
const connection = joinVoiceChannel({
channelId: interaction.member.voice.channel.id,
// voice channel id
guildId: interaction.member.voice.channel.guild.id,
// guild id
adapterCreator: interaction.member.voice.channel.guild.voiceAdapterCreator,
// guild adapterCreator
selfMute: false,
// bot Mute false
selfDeaf: true,
// bot Deaf true
});
player 생성 ( 음악 재생 플레이어 생성 )
해당 플레이어는 아래와 같은 상태입니다.
1. 통화방에 봇 이외에 접속해 있는 사람이 없을 경우 일시정지(Pause) 또는 끝냄(Stop)
const { createAudioPlayer, NoSubscriberBehavior } = require('@discordjs/voice');
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
// Pause 위치에 Stop이나 Play가 위치할수있음
},
});
2. 리소스 생성하기
const { StreamType } = require(`@discordjs/voice`);
resource = createAudioResource(
ytdl(
url,
{
filter: "audioonly",
fmt: "mp3",
highWaterMark: 1 << 62,
liveBuffer: 1 << 62,
dlChunkSize: 0,
quality: "lowestaudio"
}), {
seek: [0],
inputType: StreamType.Arbitrary
}
)
기본설정
url : 유튜브 링크
filter : "audioonly" 오디오만 가져옴
스트리밍 오류를 방지 설정
highWaterMark: 1 << 62,
liveBuffer: 1 << 62,
dlChunkSize: 0,
기타 설정
quality: "lowestaudio"
통화방 기본음질 정도의 퀄리티로 지정
inputType: StreamType.Arbitrary
리소스에 맞춰 형식지정
이외에도 opus, raw, oggopus와 같은
스트림 타입을 지정할 수 있으며
대부분은 opus 및 arbitrary를
참고하는 것 같습니다.
3. 스트리밍 제작
player.play(resource);
connection.subscribe(player);
위와 같은 코드를 작성하면
스트리밍이 시작됩니다.
4. 여러 가지 기능 및 팁
player & connecion 함수
player.pause();
//음악 일시정지
player.unpause();
//일시정지 해제
player.stop();
//음악 강제 종료 (스킵 기능 구현 가능)
player.on('stateChange', (oldState, newState) => {
//음악봇의 상태가 변할때 반응
})
connection.destroy();
//통화방 연결 끊기
connection 이벤트 함수
const { VoiceConnectionStatus, entersState } = require('@discordjs/voice');
connection.on(VoiceConnectionStatus.Disconnected, async (oldState, newState) => {
try {
await Promise.race([
entersState(connection, VoiceConnectionStatus.Signalling, 5_000),
//연결중에서 신호를 보내는중으로 바뀜 감지
entersState(connection, VoiceConnectionStatus.Connecting, 5_000),
//다시 연결이 되었는가 감지
])
} catch (error) {
connection.destroy();
//만약 다시 연견이 되지 않았을 경우 연결을 해제
}
});
player 이벤트 함수
const { AudioPlayerStatus } = require('@discordjs/voice');
player.on('error', error => {
//스트리밍중 문제가 발생할 경우 처리
});
player.on('stateChange', async (oldState, newState) => {
if (oldState.status === 'playing' && newState.status === 'idle') |
//음악이 종료되었을때 처리하는 구문
}
})
ytdl-core로 어떻게 음악을 재생할까
에 대해 알아보았습니다.
원하는 게시글이 있다면
댓글로 알려주세요!
'discord developer' 카테고리의 다른 글
interaction & message 올바른 type(Interface) 지정하는 법 (discord.js / typescript) (0) | 2023.07.28 |
---|---|
how to fix 'node-pre-gyp error' in linux or ubuntu (@discordjs/opu installing issue) (0) | 2023.07.16 |
slash commands에 쿨타임 적용하기 [discord.js] (0) | 2023.06.30 |
Slash command 디스코드 봇 제작 [discord.js] (+ interaction 오류 처리 & 안정적인 interaction 반응) (0) | 2023.06.27 |
디스코드 봇 생성하기(봇 생성하기) (0) | 2023.06.27 |