본문 바로가기

하라는 공부는 안하고/파이썬하고있네

디스코드 봇으로 노래를 틀어보자

왜냐


사실상 이걸 위해 봇을 만들기로 했다.





감을 잡아보자


classdiscord.VoiceClient(usermain_wssession_idchanneldataloop)

...

create_ffmpeg_player(filename*use_avconv=Falsepipe=Falsestderr=Noneoptions=Nonebefore_options=Noneheaders=Noneafter=None)

Creates a stream player for ffmpeg that launches in a separate thread to play audio.

The ffmpeg player launches a subprocess of ffmpeg to a specific filename and then plays that file.

You must have the ffmpeg or avconv executable in your path environment variable in order for this to work.

The operations that can be done on the player are the same as those increate_stream_player().

http://discordpy.readthedocs.io/en/latest/api.html#voice

그렇다고 한다.

보이스 클라이언트에 create_ffmpeg_player()를 사용해 플레이어를 만들고

플레이어에 start()를 해주면 되는 것 같다.

이름에서 알 수 있듯이 ffmpeg이 설치되어 있어야 한다.





코드나 짜보자


1
2
3
4
5
6
7
8
9
10
11
12
from discord.ext import commands
 
bot = commands.Bot(command_prefix='!')
 
@bot.command(pass_context=True)
async def play(ctx):
    voice = await bot.join_voice_channel(ctx.message.author.voice.voice_channel)
    player = voice.create_ffmpeg_player('music.mp3')
    player.start()
 
bot.run('토오오오오오오크으으으으으은')
 
cs

요러면 !play라고 했을 때 내가 연결되어 있는 음성채팅채널에 쫓아와 music.mp3를 틀어줄 것이다.

사실 API Reference에는 opus.load_opus()를 안하면 실행이 안된다고 하는데 잘 돌아가니까 넘어가도록 하자.

그런데 이놈의 봇이 다른 음성채널에 있을 때 부르면 안오고 에러를 뿜는다.





이걸 고쳐보자


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from discord.ext import commands
 
bot = commands.Bot(command_prefix='!')
 
async def func_comeon(ctx):
    voice = bot.voice_client_in(ctx.message.server)
    if ctx.message.author.voice.voice_channel:
        if voice:
            if voice.channel != ctx.message.author.voice.voice_channel:
                print('move to channel')
                await voice.move_to(ctx.message.author.voice.voice_channel)
        else:
            print('join to channel')
            voice = await bot.join_voice_channel(ctx.message.author.voice.voice_channel)
    else:
        await bot.say('where are you?')
        print('stay...')
    return voice
 
@bot.command(pass_context=True)
async def comeon(ctx):
    await func_comeon(ctx)
 
@bot.command(pass_context=True)
async def play(ctx):
    voice = await func_comeon(ctx)
    player = voice.create_ffmpeg_player('music.mp3')
    player.start()
 
bot.run('토오오오오오오크으으으으으은')
 
cs


if문을 덕지덕지 발라서 상황에 따라 move와 join을 하도록 했다.

좀 드러워도 나혼자 쓰는거니까 문제없다.