I am trying to create a music bot and now I want the bot to delete the current playing song after it finished playing. There’s my code:
JavaScript
x
90
90
1
import asyncio
2
3
import os
4
import discord
5
from discord.embeds import Embed
6
from discord.file import File
7
from discord.player import AudioPlayer
8
from youtube_dl.utils import smuggle_url, update_url_query
9
from youtube_search import YoutubeSearch
10
import discord
11
from discord.ext.commands import bot
12
import youtube_dl
13
from discord.ext import commands
14
from youtube_dl import YoutubeDL
15
16
youtube_dl.utils.bug_reports_message = lambda: ''
17
18
ytdl_format_options = {
19
'format': 'bestaudio/best',
20
'outtmpl': '/music_files/%(id)s.mp3',
21
'restrictfilenames': True,
22
'noplaylist': True,
23
'nocheckcertificate': True,
24
'ignoreerrors': False,
25
'logtostderr': False,
26
'quiet': True,
27
'no_warnings': True,
28
'default_search': 'auto',
29
'source_address': '0.0.0.0'
30
}
31
32
ffmpeg_options = {
33
'options': '-vn'
34
}
35
36
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
37
38
39
class YTDLSource(discord.PCMVolumeTransformer):
40
def __init__(self, source: discord.FFmpegPCMAudio, *, data: dict, volume=0.5):
41
super().__init__(source, volume)
42
43
self.data = data
44
45
self.title = data.get('title')
46
self.thumbnail = data.get('thumbnail')
47
self.url = data.get('webpage_url')
48
self.uploader = data.get('uploader')
49
self.uploader_url = data.get('uploader_url')
50
51
@classmethod
52
async def from_url(cls, url, *, loop=None, stream=False):
53
loop = loop or asyncio.get_event_loop()
54
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
55
56
if 'entries' in data:
57
# take first item from a playlist
58
data = data['entries'][0]
59
60
filename = data['url'] if stream else ytdl.prepare_filename(data)
61
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
62
63
class Music(commands.Cog):
64
def __init__(self, bot):
65
self.bot = bot
66
67
68
@commands.command()
69
async def play(self, ctx, *, url):
70
global player
71
"""Plays from a url (almost anything youtube_dl supports)"""
72
async with ctx.typing():
73
player = await YTDLSource.from_url(url, loop=self.bot.loop)
74
ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
75
76
await ctx.send("Started playing!")
77
@play.before_invoke
78
async def ensure_voice(self, ctx):
79
if ctx.voice_client is None:
80
if ctx.author.voice:
81
await ctx.author.voice.channel.connect()
82
else:
83
await ctx.send("You are not connected to a voice channel.")
84
raise commands.CommandError("Author not connected to a voice channel.")
85
elif ctx.voice_client.is_playing():
86
ctx.voice_client.stop()
87
88
def setup(client):
89
client.add_cog(Music(client))
90
It’s saving the files to a folder called “music_files” with the format videoid.mp3
I noticed that it’s logging something in the cmd when logging.basicConfig(level=logging.INFO)
is added to the main.py file under the imports, is there maybe a way to use it?
Note: The code is a modified version of basic_voice.py by Rapptz.
Edit: I found a way:
JavaScript
1
11
11
1
folder = './music_files'
2
for song in os.listdir(folder):
3
file_path = os.path.join(folder, song)
4
try:
5
if os.path.isfile(file_path) or os.path.islink(file_path):
6
os.unlink(file_path)
7
elif os.path.isdir(file_path):
8
shutil.rmtree(file_path)
9
except Exception as e:
10
print('Failed to delete %s. Reason %s' % (file_path, e))
11
Advertisement
Answer
You can remove the file with os.remove(f'PATH/{videoid}.mp3')