Python临时文件使用for循环返回NotADirectoryError

2024-09-26 22:10:52 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我创建了一个discord机器人,它可以随机挑选5首歌曲,使用youtube dl下载并播放。守则:

# Function to play music
async def radio(count, voiceClient, textChannel):
    randomSong = songs[random.randint(0, len(songs)-1)]
    # Open a temporary directory to stop downloaded files being saved
    with tempfile.TemporaryDirectory() as tempDir:
        # Use youtube-dl to get the metadata
        ydlOptions = {
            "format": "bestaudio/best",
            "outtmpl": f"{tempDir}/%(id)s.%(ext)s",
        }
        with YoutubeDL(ydlOptions) as ydl:
            realLinkRaw = ydl.extract_info(randomSong, download=True)
            videoID = realLinkRaw["id"]
            videoExtension = realLinkRaw["ext"]
        # Test if its the first song so a message can be displayed
        if count == 0:
            # First song so output a message describing it
            title = realLinkRaw["title"]
            await textChannel.send(f"Up next, {title}")
        # Play the song
        tempFileName = f"{tempDir}/{videoID}.{videoExtension}"
        voiceClient.play(FFmpegPCMAudio(tempFileName))
        # Wait for the duration of the song before repeating
        await asyncio.sleep(realLinkRaw["duration"])


# Function to loop continuously and run the main program
async def mainProg(voiceClient, textChannel):
    # Create infinite loop to run main program
    while True:
        # Output a random radio message
        await textChannel.send(radioLines[random.randint(0, len(radioLines)-1)])
        # Play 5 random songs
        for count in range(5):
            await radio(count, voiceClient, textChannel)

但是,当前在播放完第一首歌曲后,我出现以下错误:

NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\Users\\jacka\\AppData\\Local\\Temp\\tmpzodsgvvw\\SH_pDjcQx2w.m4a'

整个回溯: https://pastebin.com/2HVJvS5m


Tags: thetomessagesongtitlecountrandomawait

热门问题