(Discord.py) 如何检查机器人是否已经在语音通道中播放音频?

时间:2021-03-25 07:59:59

标签: python audio discord

已经使用 Discord.py 库创建了一个 Discord 机器人。 它根据给定的命令播放声音 !sound 但是当它忙于播放声音并且调用了新声音时,我希望它停止并播放下一个声音。但我不知道检查机器人是否已经在播放声音的功能? 有人给点建议吗?

这是我播放声音的代码:

@client.command(pass_context= True)
async def sound(ctx, message):
  serverid = ctx.message.guild.id
  newname = str(serverid) + "_" + message + ".mp3" 
  print(newname)
  print(serverid)
  mp3 = message+'.mp3' #take message (soundname) and add .mp3
  mp3 = 'sounds/'+mp3  #Add /sounds folder
  print(mp3)
  if(path.exists(mp3)):#check if file exists
    source = FFmpegPCMAudio(mp3) #set FFMPEG source
    if(ctx.author.voice is None): #check if author is in voice channel
      await ctx.send("Please join a voice channel first!")
      print("Author not in voicechat") 
    else:               #otherwist, get authors voice channel UID
      print("Author in voicechat") 
      channel = ctx.author.voice.channel
      if(ctx.voice_client is None): #check if bot is already in voicechannel
        print("Bot is not connected, connecting...")
        voice = await channel.connect()   #if not -> Connect
        voice.play(source)                #and Play
      else:                               #if already connected
        voice = ctx.voice_client          #get UID of voice channel
        print("Bot is connected to voicechat")
        voice.play(source)                #play without Reconnecting
  else:
    await ctx.send("Uh Oh, That chip does not exist")#if file doesn't exist
  print("-----------------------------------")

1 个答案:

答案 0 :(得分:0)

你可以就这样停下来,我想:

try:
    voice_channel = ctx.message.guild.voice_client
    voice_channel.stop()
    #run code 
except:
    #run code

或检查音频是否正在播放:

import asyncio

async def duration():
    global is_playing
    is_playing = true
    await asyncio.sleep(duration)
    is_playing = false

在开始播放音频后立即运行该功能,然后使用 is_playing 检查歌曲是否正在播放。 希望这有效。