Why is my bot not replacing the file if it already exists?

Viewed 86

I'm trying to follow this tutorial on how to build a music bot for discord.

I'm using pycharm 2021.1.1 and anaconda 3 as my interpreter (python 3.7) on win10.

I added some changes but none should cause this behavior: The bot tries to download but fails because the file already exists. The file is most likely song.mp3 but it is supposed to be deleted in the line: (I tried both versions, none works, I think it is the same issue)

  1. Why is the file song.mp3 not deleted?
  2. Have I done any other mistakes that I'm unaware of and would prevent the bot from playing music?
if song_there:
#        os.remove('song.mp3')
        os.remove(os.path.join(os.getcwd(),"song.mp3"))

Minimal code:

import discord
from discord.ext import commands
import youtube_dl #for url music command
import os

client = commands.Bot(command_prefix = '><')

#play music from url
@client.command(aliases = ['p'])
async def playMusic(ctx, vcName, url : str): #play music file
    song_there = os.path.isfile('song.mp3')

    try:
        if song_there:
#            os.remove('song.mp3')
            os.remove(os.path.join(os.getcwd(),"song.mp3"))
    except PermissionError:
        await ctx.send('A song is currently playing')
        return

    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }]
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
    for file in os.listdir('./'):
        os.rename(file, 'song.mp3')
    voice.play(discord.FFmpegPCAudio('song.mp3'))
    voiceChannel = discord.utils.get(ctx.guild.channels, name=str(vcName)) 
    await voiceChannel.connect()
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    client.run('token')

Errors:

[youtube] bvNZeh6f8vE: Downloading webpage

[download] Destination: title-bvNZeh6f8vE.webm

[download] 100% of 3.95MiB in 00:00                  

[ffmpeg] Destination: title-bvNZeh6f8vE.mp3

Ignoring exception in command playMusic:

Traceback (most recent call last):

File "C:\ProgramData\Anaconda3\lib\site-packages\discord\ext\commands\core.py", line 85, in 
wrapped

ret = await coro(*args, **kwargs)

File "path/tut-bot.py", line 42, in playMusic
os.rename(file, 'song.mp3')

FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'music bot 
1.py' -> 'song.mp3'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

 File "C:\ProgramData\Anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 939, in 
invoke

await ctx.command.invoke(ctx)

File "C:\ProgramData\Anaconda3\lib\site-packages\discord\ext\commands\core.py", line 863, in 
invoke

await injected(*ctx.args, **ctx.kwargs)

File "C:\ProgramData\Anaconda3\lib\site-packages\discord\ext\commands\core.py", line 94, in 
wrapped

raise CommandInvokeError(exc) from exc

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: FileExistsError: 
[WinError 183] Cannot create a file when that file already exists: 'music bot 1.py' -> 
'song.mp3'

Deleting original file title-bvNZeh6f8vE.webm (pass -k to keep)
1 Answers

I think the reason why it's not removed is because your song_there = os.path.isfile('song.mp3') Try to replace it with song_there = os.path.exists('song.mp3') if this path to the song.mp3 is correct.

Try to use os.path.exists() instead of os.path.isfile(), isfile() return True only of the given path is a file.

Related