机器人播放后如何删除mp3文件
How to delete mp3 file after the bot played it
我正在尝试创建一个音乐机器人,现在我希望该机器人在播放完当前播放的歌曲后将其删除。这是我的代码:
import asyncio
import os
import discord
from discord.embeds import Embed
from discord.file import File
from discord.player import AudioPlayer
from youtube_dl.utils import smuggle_url, update_url_query
from youtube_search import YoutubeSearch
import discord
from discord.ext.commands import bot
import youtube_dl
from discord.ext import commands
from youtube_dl import YoutubeDL
youtube_dl.utils.bug_reports_message = lambda: ''
ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': '/music_files/%(id)s.mp3',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0'
}
ffmpeg_options = {
'options': '-vn'
}
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source: discord.FFmpegPCMAudio, *, data: dict, volume=0.5):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
self.thumbnail = data.get('thumbnail')
self.url = data.get('webpage_url')
self.uploader = data.get('uploader')
self.uploader_url = data.get('uploader_url')
@classmethod
async def from_url(cls, url, *, loop=None, stream=False):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def play(self, ctx, *, url):
global player
"""Plays from a url (almost anything youtube_dl supports)"""
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop)
ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send("Started playing!")
@play.before_invoke
async def ensure_voice(self, ctx):
if ctx.voice_client is None:
if ctx.author.voice:
await ctx.author.voice.channel.connect()
else:
await ctx.send("You are not connected to a voice channel.")
raise commands.CommandError("Author not connected to a voice channel.")
elif ctx.voice_client.is_playing():
ctx.voice_client.stop()
def setup(client):
client.add_cog(Music(client))
它正在将文件保存到名为“music_files”的文件夹中,格式为 videoid.mp3
我注意到当 logging.basicConfig(level=logging.INFO)
添加到 imports 下的 main.py 文件时,它在 cmd 中记录了一些东西,有没有办法使用它?
注意:该代码是 Rapptz 对 basic_voice.py 的修改版本。
编辑:我找到了一个方法:
folder = './music_files'
for song in os.listdir(folder):
file_path = os.path.join(folder, song)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason %s' % (file_path, e))
您可以使用 os.remove(f'PATH/{videoid}.mp3')
删除文件
我正在尝试创建一个音乐机器人,现在我希望该机器人在播放完当前播放的歌曲后将其删除。这是我的代码:
import asyncio
import os
import discord
from discord.embeds import Embed
from discord.file import File
from discord.player import AudioPlayer
from youtube_dl.utils import smuggle_url, update_url_query
from youtube_search import YoutubeSearch
import discord
from discord.ext.commands import bot
import youtube_dl
from discord.ext import commands
from youtube_dl import YoutubeDL
youtube_dl.utils.bug_reports_message = lambda: ''
ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': '/music_files/%(id)s.mp3',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0'
}
ffmpeg_options = {
'options': '-vn'
}
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source: discord.FFmpegPCMAudio, *, data: dict, volume=0.5):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
self.thumbnail = data.get('thumbnail')
self.url = data.get('webpage_url')
self.uploader = data.get('uploader')
self.uploader_url = data.get('uploader_url')
@classmethod
async def from_url(cls, url, *, loop=None, stream=False):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def play(self, ctx, *, url):
global player
"""Plays from a url (almost anything youtube_dl supports)"""
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop)
ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send("Started playing!")
@play.before_invoke
async def ensure_voice(self, ctx):
if ctx.voice_client is None:
if ctx.author.voice:
await ctx.author.voice.channel.connect()
else:
await ctx.send("You are not connected to a voice channel.")
raise commands.CommandError("Author not connected to a voice channel.")
elif ctx.voice_client.is_playing():
ctx.voice_client.stop()
def setup(client):
client.add_cog(Music(client))
它正在将文件保存到名为“music_files”的文件夹中,格式为 videoid.mp3
我注意到当 logging.basicConfig(level=logging.INFO)
添加到 imports 下的 main.py 文件时,它在 cmd 中记录了一些东西,有没有办法使用它?
注意:该代码是 Rapptz 对 basic_voice.py 的修改版本。
编辑:我找到了一个方法:
folder = './music_files'
for song in os.listdir(folder):
file_path = os.path.join(folder, song)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason %s' % (file_path, e))
您可以使用 os.remove(f'PATH/{videoid}.mp3')