Skip to main content
 首页 » 编程设计

python之如何让我的 discord 机器人在加入语音 channel 时立即播放音频文件,例如 airhorn solutions 机器人

2025年02月15日8cyq1162

@client.command(pass_context=True) 
async def joinvoice(ctx): 
    """Joins user's voice channel""" 
    author = ctx.message.author 
    voice_channel = author.voice_channel 
    vc = await client.join_voice_channel(voice_channel) 

这就是我目前让机器人加入语音 channel 的方式,我如何让它在加入时播放音频文件?我几乎没有经验,到目前为止,整个机器人都是通过提问和大量谷歌搜索来编码的。非常感谢任何帮助,谢谢!

请您参考如下方法:

您必须创建一个 StreamPlayer 并使用播放器操作来播放音频。这是我编写的一些示例代码,用于与我的 discord 机器人一起播放 vuvuzela:

@client.command( 
    name='vuvuzela', 
    description='Plays an awful vuvuzela in the voice channel', 
    pass_context=True, 
) 
async def vuvuzela(context): 
    # grab the user who sent the command 
    user = context.message.author 
    voice_channel = user.voice.voice_channel 
    channel = None 
    if voice_channel != None: 
        channel = voice_channel.name 
        await client.say('User is in channel: ' + channel) 
        vc = await client.join_voice_channel(voice_channel) 
        player = vc.create_ffmpeg_player('vuvuzela.mp3', after=lambda: print('done')) 
        player.start() 
        while not player.is_done(): 
            await asyncio.sleep(1) 
        player.stop() 
        await vc.disconnect() 
    else: 
        await client.say('User is not in a channel.')