import os
import re
import urllib.request
import youtube_dl
import shutil
import discord
from discord.ext import commands
from discord.utils import get
bot = commands.Bot(command_prefix='g.')
token = '<mytoken>'
queues = {} # for tracking queued song numbers
# -----------------------------
# Function to check and play next song
# -----------------------------
def check_queue(ctx, voice):
Queue_infile = os.path.isdir("./Queue")
if Queue_infile:
DIR = os.path.abspath(os.path.realpath("Queue"))
length = len(os.listdir(DIR))
if length > 0:
first_file = os.listdir(DIR)[0]
song_path = os.path.abspath(os.path.realpath("Queue") + "\\" + first_file)
if os.path.isfile("song.mp3"):
os.remove("song.mp3")
shutil.move(song_path, "./song.mp3")
voice.play(
discord.FFmpegPCMAudio("song.mp3"),
after=lambda e: check_queue(ctx, voice)
)
voice.source = discord.PCMVolumeTransformer(voice.source)
voice.source.volume = 0.3
print("Playing next queued song...")
else:
queues.clear()
print("Queue empty, stopping.")
else:
queues.clear()
print("No Queue folder found.")
# -----------------------------
# PLAY command
# -----------------------------
@bot.command(pass_context=True)
async def play(ctx, *args: str):
search = '+'.join(args)
if search.strip() == "":
await ctx.send("Uso: g.play (Video)")
return
html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search)
video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())
url = "https://www.youtube.com/watch?v=" + video_ids[0]
print("Found URL:", url)
# remove old song if exists
if os.path.isfile("song.mp3"):
try:
os.remove("song.mp3")
queues.clear()
print("Removed old song file")
except PermissionError:
await ctx.send("Error: Ya estoy poniendo musica! Usa g.queue para agregar más canciones.")
return
# clear old queue folder
if os.path.isdir("./Queue"):
try:
shutil.rmtree("./Queue")
print("Removed old Queue Folder")
except:
pass
await ctx.send("Preparando cancion...")
voice = get(bot.voice_clients, guild=ctx.guild)
if not voice:
if ctx.author.voice:
channel = ctx.message.author.voice.channel
voice = await channel.connect()
else:
await ctx.send("⚠️ No estas en un canal de voz.")
return
ydl_opts = {
'format': 'bestaudio/best',
'quiet': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
print("Downloading audio now\n")
ydl.download([url])
for file in os.listdir("./"):
if file.endswith(".mp3"):
name = file
os.rename(file, "song.mp3")
voice.play(
discord.FFmpegPCMAudio("song.mp3"),
after=lambda e: check_queue(ctx, voice)
)
voice.source = discord.PCMVolumeTransformer(voice.source)
voice.source.volume = 0.3
await ctx.send(f"▶️ Reproduciendo: {url}")
# -----------------------------
# QUEUE command
# -----------------------------
@bot.command(pass_context=True)
async def queue(ctx, *searchs):
search = '+'.join(searchs)
if not os.path.isdir("./Queue"):
os.mkdir("Queue")
DIR = os.path.abspath(os.path.realpath("Queue"))
q_num = len(os.listdir(DIR)) + 1
while q_num in queues:
q_num += 1
queues[q_num] = q_num
queue_path = os.path.abspath(os.path.realpath("Queue") + f"\\song{q_num}.%(ext)s")
ydl_opts = {
'format': 'bestaudio/best',
'quiet': True,
'outtmpl': queue_path,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192'
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search)
video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())
url = "https://www.youtube.com/watch?v=" + video_ids[0]
print("Queueing:", url)
ydl.download([url])
await ctx.send("➕ Añadiendo canción " + str(q_num) + " a la lista!")
# -----------------------------
# SKIP command
# -----------------------------
@bot.command()
async def skip(ctx):
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_playing():
voice.stop() # triggers check_queue through after callback
await ctx.send("⏭️ Canción saltada.")
else:
await ctx.send("⚠️ No hay canción reproduciéndose.")
# -----------------------------
# On Ready
# -----------------------------
@bot.event
async def on_ready():
print(f"Bot {bot.user} has connected to discord!")
bot.run(token)