【发布时间】:2021-11-27 00:34:27
【问题描述】:
使用 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("-----------------------------------")
【问题讨论】:
-
"但是我不知道有一个函数可以检查机器人是否已经在播放声音?"为什么不只是记住机器人正在播放声音?你知道它什么时候开始播放声音(因为这是导致这种情况发生的代码!)并且你大概知道声音持续了多长时间。是吗?