python - 如果文件已经存在,为什么我的机器人不替换文件?

标签 python discord discord.py

我正在尝试关注这个 tutorial关于如何为 discord 构建音乐机器人。

我在 win10 上使用 pycharm 2021.1.1 和 anaconda 3 作为我的解释器 (python 3.7)。

我添加了一些更改,但都不会导致此行为:机器人尝试下载但失败,因为文件已经存在。该文件很可能是 song.mp3 但它应该在以下行中删除:(我尝试了两个版本,都没有用,我认为这是同一个问题)

  1. 为什么song.mp3文件没有被删除?
  2. 我是否犯了任何其他我没有意识到并且会阻止机器人播放音乐的错误?
if song_there:
#        os.remove('song.mp3')
        os.remove(os.path.join(os.getcwd(),"song.mp3"))

最少的代码:

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')

错误:

[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)

最佳答案

我认为它没有被删除的原因是因为你的 song_there = os.path.isfile('song.mp3') 尝试将其替换为 song_there = os.path.exists ('song.mp3') 如果到 song.mp3 的这条路径是正确的。

尝试使用os.path.exists()代替os.path.isfile(),isfile()只返回True给定路径是一个文件.

关于python - 如果文件已经存在,为什么我的机器人不替换文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67995219/

相关文章:

javascript - 使用discord.js检测图像并响应

javascript - Discord.js:无效的位域标志或数字:GUILDS

python - 检查用户列表是否对消息 discord.py rewrite 作出 react

python 博托 : How do you specify a subnet id AND a security group?

python - 如何使用 python 从 GUI 传递 SQL 查询并获取结果并在表中显示结果

python - celery 的apply_async 是线程还是进程?

javascript - 统计文本 channel 、语音 channel 、所有 channel 和角色

python - 在discord.py中是否有类似于discord.js中的streamTime的东西?

python - Discord.Py Opus Heroku 问题

python - 如何在 Spark 中控制输出拼花文件的大小