본문 바로가기
Discord/Discord Bot Python

Discord Bot 만들기 - 유튜브 음악 재생 봇

by 깐테 2023. 5. 18.

Discord Bot 만들기 - 음성 채널 입장하기

 

Discord Bot 만들기 - 음성 채널 입장하기

디스코드 봇을 사용해본 경험이 있다면, 유튜브 혹은 사운드 클라우드 등의 앱에서 음악을 재생해주는 봇을 사용해 봤을 수 있다. 여기서는 그러한 음악 재생 봇들의 기본이 될 수 있는 방법인 "

kante-kante.tistory.com

기존 음성 채널에 입장시키는 봇은 위 링크를 참조.

 

 

 


2023.09.24

해당 원본 코드의 기존 !play, !yt, !stream을 삭제하고

!play [유튜브_링크]로 변경하였습니다.


2024.03.10

!join 명령어가 실행되지 않는 문제를 해결했습니다.

!pause , !resume 명령어를 추가했습니다.

 

*

!pause: 재생 중인 음악을 일시 정지합니다.

!resume: 일시 정지한 음악을 다시 재생합니다.


 

Basic - 디스코드 음악 재생 봇 만들기

https://github.com/Rapptz/discord.py/blob/master/examples/basic_voice.py

 

GitHub - Rapptz/discord.py: An API wrapper for Discord written in Python.

An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.

github.com

  • 해당 봇은 Discord.py Example과 동일한 예시이므로, 원 소스코드를 참고하려면 위 링크를 참조한다.

 

⚠️ 실행 전 유의사항

  • ffmpeg가 컴퓨터에 설치되어 있거나 파이썬 설치 경로에 ffmpeg.exe 파일이 있어야 한다.
  • FFMPEG 설치는 아래 사이트 참조.

▒ Blog Of Life ▒ : 네이버 블로그

 

파이썬#92 - 파이썬과 ffmpeg 로 동영상 썸네일 콜라주 만들기

이번 포스트에서는 동영상 파일에서 여러장의 이미지를 추출하여 한장의 콜라주, 즉 미리보기 스크린샷을 ...

blog.naver.com

  • 파이썬 설치 경로는 cmd → python → import sys → sys.executable 입력하여 확인한다.
C:\\user> python
>>> import sys
>>> sys.executable

**** youtube_dl의 extract id 관련 오류로 인해 yt_dlp 설치

pip install yt_dlp

 

💡 만약 PyNaCl 오류가 발생하거나 설치가 되지 않는다면?

  • CMD 관리자 권한으로 실행 → py -3 -m pip install -U discord.py[voice]
py -3 -m pip install discord.py[voice]

 

 

디스코드에서 봇을 이용하여 음악 재생하기

 

사용 전 설정하기

 

먼저 이 코드를 실행시키기 위해서는 디스코드 개발자 포털 - Bot 탭에서 message contents가 사용 설정 되어있어야 하고, yt_dlp를 import 시켜야 한다.

Message Content INTENT에 사용 설정

https://github.com/yt-dlp/yt-dlp

 

GitHub - yt-dlp/yt-dlp: A youtube-dl fork with additional features and fixes

A youtube-dl fork with additional features and fixes - GitHub - yt-dlp/yt-dlp: A youtube-dl fork with additional features and fixes

github.com

 

YT_DLP

  • 유튜브 링크를 읽어 와서 해당 영상을 재생시켜주는 라이브러리
  • 원본 소스코드에서는 youtube_dl 라이브러리를 사용하였지만, extract id 관련 오류가 있기 때문에 youtube_dl과 호환되는 라이브러리 사용.

 

코드 설명

join, play, yt, stream 등등의 함수를 지정해주었지만, 간략하게 소스코드에 설명이 되어 있기도 하고

디스코드 내에서 커맨드로 확인해보는 것이 빠를 것이다.

 

주요 코드 부분만 살펴보자면

 

# youtube 음악과 로컬 음악의 재생을 구별하기 위한 클래스 작성.
class YTDLSource(discord.PCMVolumeTransformer):
    def __init__(self, source, *, data, volume=0.5):
        super().__init__(source, volume)

        self.data = data

        self.title = data.get('title')
        self.url = data.get('url')

    @classmethod
    async def from_url(cls, url, *, loop=None, stream=False):
        loop = loop or asyncio.get_event_loop()
        data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))

        if 'entries' in data:
            # take first item from a playlist
            data = data['entries'][0]

        filename = data['url'] if stream else ytdl.prepare_filename(data)
        return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
  • YTDL로 시작하는 클래스 명 혹은 함수 명은 모두 yt_dlp 라이브러리를 사용하기 위한 설정 또는 실행 코드라고 생각하면 된다.
  • data:  추후 유튜브 링크가 저장될 변수 명이고, 이 변수명에서 제목, url 정보를 추출한다.

 

 

bot = commands.Bot(
    command_prefix=commands.when_mentioned_or("!"),
    description='Relatively simple music bot example',
    intents=intents,
)

이 부분의 코드에서는 command를 어떤 텍스트로 시작할지를 지정해 줄 수 있다.

commands.when_mentioned_or("") 부분에 커맨드 시작 텍스트를 지정해주면 된다.

 

본인은 !로 지정했다.

 

 

@play.before_invoke
@yt.before_invoke
@stream.before_invoke
async def ensure_voice(self, ctx):
    if ctx.voice_client is None:
        if ctx.author.voice:
            await ctx.author.voice.channel.connect()
        else:
            await ctx.send("You are not connected to a voice channel.")
            raise commands.CommandError("Author not connected to a voice channel.")
    elif ctx.voice_client.is_playing():
        ctx.voice_client.stop()

이 코드는 play, stream, yt 커맨드를 실행하기 이전에 체크하는 코드라고 생각하면 된다.

 

음성 채팅방에 사람이 없으면 봇을 입장시키지 않고, 사람이 있다면 입장시킨다.

 

 

 

전체 코드

# This example requires the 'message_content' privileged intent to function.

import asyncio

import discord
import yt_dlp as youtube_dl

from discord.ext import commands
from dico_token import Token

# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambda: ''


ytdl_format_options = {
    'format': 'bestaudio/best',
    'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '0.0.0.0',  # bind to ipv4 since ipv6 addresses cause issues sometimes
}

ffmpeg_options = {
    'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
    'options': '-vn',
}

ytdl = youtube_dl.YoutubeDL(ytdl_format_options)


# youtube 음악과 로컬 음악의 재생을 구별하기 위한 클래스 작성.
class YTDLSource(discord.PCMVolumeTransformer):
    def __init__(self, source, *, data, volume=0.5):
        super().__init__(source, volume)

        self.data = data

        self.title = data.get('title')
        self.url = data.get('url')

    @classmethod
    async def from_url(cls, url, *, loop=None, stream=False):
        loop = loop or asyncio.get_event_loop()
        data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))

        if 'entries' in data:
            # take first item from a playlist
            data = data['entries'][0]

        filename = data['url'] if stream else ytdl.prepare_filename(data)
        return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)


# 음악 재생 클래스. 커맨드 포함.
class Music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def join(self, ctx):
        """Joins a voice channel"""
        
        channel = ctx.author.voive.channel

        if ctx.voice_client is not None:
            return await ctx.voice_client.move_to(channel)

        await channel.connect()

   
    @commands.command()
    async def play(self, ctx, *, url):
        """Streams from a url (same as yt, but doesn't predownload)"""

        async with ctx.typing():
            player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
            ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)

        await ctx.send(f'Now playing: {player.title}')

    @commands.command()
    async def volume(self, ctx, volume: int):
        """Changes the player's volume"""

        if ctx.voice_client is None:
            return await ctx.send("Not connected to a voice channel.")

        ctx.voice_client.source.volume = volume / 100
        await ctx.send(f"Changed volume to {volume}%")

    @commands.command()
    async def stop(self, ctx):
        """Stops and disconnects the bot from voice"""

        await ctx.voice_client.disconnect()
        
    @commands.command()
    async def pause(self, ctx):
        ''' 음악을 일시정지 할 수 있습니다. '''

        if ctx.voice_client.is_paused() or not ctx.voice_client.is_playing():
            await ctx.send("음악이 이미 일시 정지 중이거나 재생 중이지 않습니다.")
            
        ctx.voice_client.pause()
            
    @commands.command()
    async def resume(self, ctx):
        ''' 일시정지된 음악을 다시 재생할 수 있습니다. '''

        if ctx.voice_client.is_playing() or not ctx.voice_client.is_paused():
            await ctx.send("음악이 이미 재생 중이거나 재생할 음악이 존재하지 않습니다.")
            
        ctx.voice_client.resume()

    @play.before_invoke
    async def ensure_voice(self, ctx):
        if ctx.voice_client is None:
            if ctx.author.voice:
                await ctx.author.voice.channel.connect()
            else:
                await ctx.send("You are not connected to a voice channel.")
                raise commands.CommandError("Author not connected to a voice channel.")
        elif ctx.voice_client.is_playing():
            ctx.voice_client.stop()


intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(
    command_prefix=commands.when_mentioned_or("!"),
    description='Relatively simple music bot example',
    intents=intents,
)


@bot.event
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')
    print('------')


async def main():
    async with bot:
        await bot.add_cog(Music(bot))
        await bot.start(Token)


asyncio.run(main())

사용 방법

!play 유튜브_링크

ex) !play https://www.youtube.com/~

 

커맨드에 관한 설명을 필요로 한다면 !help 명령어를 이용하면 간략한 설명 메시지를 출력하게 할 수 있다.

 

 

 

 

결과

 

반응형