当有人加入语音聊天时,如何使Discord机器人加入语音通道并播放音频文件

时间:2020-05-19 18:39:49

标签: python-3.x audio discord.py-rewrite

我当前的项目

我正在尝试使Discord机器人在有人加入Discord语音聊天时播放特定的音频文件(.mp3或.ogg)。

我的问题

我不知道该如何实现。

1 个答案:

答案 0 :(得分:1)

我认为这应该有效。您必须安装ffmpeg并安装所需的模块,但如果有任何问题,请告诉我。

import discord
import audioread
import time

@client.event
async def on_voice_state_update(member: discord.Member, before, after):
#replace this with the path to your audio file
    path = r"/path/to/file.mp3"

    vc_before = before.channel
    vc_after = after.channel
    if vc_before == vc_after:
        return
    if vc_before is None:
        channel = member.voice.channel
        vc = await channel.connect()
        sleep(.5)
        vc.play(discord.FFmpegPCMAudio(path))
        with audioread.audio_open(path) as f:
            #Start Playing
            sleep(f.duration)
        await vc.disconnect()

    elif vc_after is None:
        return
    else:
        channel = member.voice.channel
        vc = await channel.connect()
        sleep(.5)
        vc.play(discord.FFmpegPCMAudio(path))
        with audioread.audio_open(path) as f:
            #Start Playing
            sleep(f.duration)
        await vc.disconnect()