3

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)
Lars
  • 31
  • 2

1 Answers1

1

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.

Zichzheng
  • 1,090
  • 7
  • 25
  • 1
    I updated my answer. Can you use python console to see whether `os.path.exists('song.mp3')` is True or not, you will need to type `import os` first. – Zichzheng Jun 16 '21 at 01:46
  • It's a step in the right direction, but it now gives me the `except PermissionError` so it does not exist. I don't understand how can it on one hand not exist but fail to download because it already exists... – Lars Jun 16 '21 at 01:59
  • 1
    For `except PermissionError`, I think this is because the for the folder where the song.mp3 is. You only have read-only access. So, the os.remove() caused this error. Try just use File Explorer and go to this path and right-click the folder to its properties and uncheck read-only. For connection, you might want to check whether you have everything right like channel id. – Zichzheng Jun 16 '21 at 02:08
  • I think the problem is that windows prevents python from deleting the directory "song.mp3". Any idea how to overcome that? – Lars Jun 16 '21 at 02:35
  • 1
    Try just use File Explorer and go to this path and right-click the folder to its properties and uncheck read-only. – Zichzheng Jun 16 '21 at 04:44
  • 1
    I think this URL: can help: https://stackoverflow.com/questions/1213706/what-user-do-python-scripts-run-as-in-windows . Also, you can try to use os.rename(old name, new name) – Zichzheng Jun 16 '21 at 17:14
  • You're right. Win10 ignored when I unchecked the 'to read only' marker for the folders. I'll ask again if I manage to solve this issue – Lars Jun 16 '21 at 18:19