我有一个 Discord 机器人,可以根据命令在语音通道中播放音频文件。当该文件不存在时,我想通过处理它try / except- 问题是,
discord.FFmpegPCMAudio只是res/mp3s/asff.mp3: No such file or directory直接打印到控制台,而不是触发该except部分。
但我不明白的是:当我放入open(filename, r)同一函数时,它会正确返回[Errno 2] No such file or directory并触发我的except处理。
为什么同一位置的两个函数都尝试访问文件会给我的异常处理带来两个不同的结果,我该如何防止它?我的第一个简单的解决方案是os.path.exist()在调用函数之前手动执行,但我想知道为什么我首先会遇到这个问题。
这大致就是我的代码的样子,当然不能直接复制,因为你需要一个正在运行的不和谐机器人......
async def playAudioFile(message, audiofile, volume):
with open('res/mp3s/{}.mp3'.format(audiofile.lower()), "r") as f:
print(f.read()) #returns error towards my exception handler as expected
if volume is None:
voice_channel = message.author.voice.channel
vc = await voice_channel.connect()
vc.play(discord.FFmpegPCMAudio('res/mp3s/{}.mp3'.format(audiofile.lower()))) #prints directly into console, ignores my exception handler
while vc.is_playing() == True:
pass
else:
for x in bot.voice_clients:
if (x.guild == message.guild):
await x.disconnect()
@commands.command()
async def play(self, ctx, argument, volume):
try:
await playAudioFile(audiofile=argument, message=ctx.message, volume=volume):
except Exception as e:
print("Ooops!" + str(e))
函数式编程
相关分类