简体   繁体   中英

How to make a discord bot loop audio? [discord.py]

I want to make a bot play a piece of audio and, when the audio finishes, it will replay the audio.

What I have:

@client.command()
async def play(ctx):
await ctx.channel.purge(limit=1)
channel = ctx.author.voice.channel
if channel:
    print(channel.id)
    await channel.connect()
guild = ctx.guild
audio_source = discord.FFmpegPCMAudio('audio.mp3')
voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild=guild)
if not voice_client.is_playing():
    voice_client.play(audio_source, after=None)

discord.VoiceClient.Play() has an after parameter that is called when the audio stream ends. Normally, it should be used to display error messages but you can use it to repeat the song like so:

@client.command()
async def play(ctx):
    await ctx.channel.purge(limit=1)
    channel = ctx.author.voice.channel
    voice = get(self.bot.voice_clients, guild=ctx.guild)

    def repeat(guild, voice, audio):
        voice.play(audio, after=lambda e: repeat(guild, voice, audio))
        voice.is_playing()

    if channel and not voice.is_playing():
        audio = discord.FFmpegPCMAudio('audio.mp3')
        voice.play(audio, after=lambda e: repeat(ctx.guild, voice, audio))
        voice.is_playing()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM