import discord
import youtube_dl
from discord.ext import commands
-----------------------------------------------
#cat.command(pass_context=True)
async def play(ctx):
if not ctx.message.author.voice:
await ctx.send('you are not connected to a voice channel')
return
else:
channel = ctx.message.author.voice.channel
await channel.connect()
server = ctx.message.guild
voice_channel = server.voice.client
async with ctx.typing():
player = await YTDLSource.from_url(url, loop = client.loop)
voice_channel.play(player)
await ctx.send(f'**Music:**{player.title}')
Is there any way to fix this error?
AttributeError: 'Guild' object has no attribute 'voice'
Check this working example.
import discord
import youtube_dl
from discord.ext import commands
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
def endSong(guild, path):
os.remove(path)
#cat.command(pass_context=True)
async def play(ctx, url):
if not ctx.message.author.voice:
await ctx.send('you are not connected to a voice channel')
return
else:
channel = ctx.message.author.voice.channel
voice_client = await channel.connect()
guild = ctx.message.guild
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
file = ydl.extract_info(url, download=True)
path = str(file['title']) + "-" + str(file['id'] + ".mp3")
voice_client.play(discord.FFmpegPCMAudio(path), after=lambda x: endSong(guild, path))
voice_client.source = discord.PCMVolumeTransformer(voice_client.source, 1)
await ctx.send(f'**Music: **{url}')
Optional, useful function
If you want you can make your bot leave the voice channel after the song stops playing. Add this at the end of your code:
while voice_client.is_playing():
await asyncio.sleep(1)
else:
await voice_client.disconnect()
print("Disconnected")
Try to replace if not ctx.message.author.voice: with if 'voice' not in ctx.message.author:
Related
I have everything setup, and everything installed properly. When I try to run the bot with !play command, the traceback is just on downloading web page. no errors at all. I'm suspecting it might be an error with the source, but I am not sure.
#commands.command()
async def play(self, ctx, url):
if ctx.voice_client is None:
if ctx.author.voice:
await ctx.author.voice.channel.connect()
else:
await ctx.send("You're not connected to a voice channel.")
raise commands.CommandError("Author not connected to voice channel.")
elif ctx.voice_client.is_playing():
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnected_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format':"bestaudio"}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info["formats"][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
I changed your code a little bit.
You will need the YoutubeSearch module
pip install youtube-search
from youtube_search import YoutubeSearch
#client.command()
async def play(ctx,*, song):
voice_state = ctx.member.voice
if voice_state == None:
await ctx.send("You are not in a voice channel!")
return
if voice_state != None:
await ctx.author.voice.channel.connect()
results = YoutubeSearch(song, max_results=1).to_dict()
print(results)
song_name = results[0]['title']
url_suffix = results[0]['url_suffix']
url = "https://youtube.com"+url_suffix
playinge = discord.Embed(
title = "Now Playing",
description = f"[{song_name}]({url})",
color = discord.Colour.green()
)
ydl_opts = {'format': 'bestaudio'}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
URL = info['formats'][0]['url']
vc = ctx.voice_client
vc.play(discord.FFmpegPCMAudio(URL))
await ctx.send(embed=playinge)
Try this.
Basically I made a bot that just simply plays music, I made a command that plays the song so you do ?play [url of song] and it will play, now I'm working on a ?search command that you can enter the keyword and it will play the song, after alot of errors I got it to find the songs when you typed them. But it doesn't stream the sound over the audio (but it does though when you use the ?play command) This is my code:
import discord
from discord.ext import commands
import youtube_dl
import requests
class music(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("Join a voice channel dumb fuck")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
#commands.command()
async def disconnect(self,ctx):
await ctx.voice_client.disconnect()
#commands.command()
async def play(self,ctx,url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format':"bestaudio"}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
#commands.command()
async def search(self, ctx, arg):
ctx.voice_client.stop()
try:
requests.get("" + str(arg))
except: arg = " " + str(arg)
else: arg = "" + str(arg)
YDL_OPTIONS = {'format':"bestaudio"}
vc = ctx.voice_client
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(f"ytsearch:{arg}", download=False)['entries'][0]
url2 = info['formats'][0]['url']
return {'source': info['formats'][0]['url'], 'title': info['title']}
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
#commands.command()
async def pause(self,ctx):
await ctx.voice_client.pause()
await ctx.send("PAUSED")
#commands.command()
async def resume(self,ctx):
await ctx.voice_client.resume()
await ctx.send("RESUMED")
def setup(client):
client.add_cog(music(client))
The console doesn't give any errors it just says this:
[download] Downloading playlist: superidol
[youtube:search] query " superidol": Downloading page 1
[youtube:search] playlist superidol: Downloading 1 videos
[download] Downloading video 1 of 1
[youtube] chY9p-XLHHk: Downloading webpage
[download] Finished downloading playlist: superidol
Don't know the answer but from the things you said and what the console sent, I think it downloaded the webpage, not the video.
If that the case there's no way of playing a webpage so this can be the issue.
PS: I sent an answer, not a comment since I dont have enough reputation.
I'm making a discord bot. But I'm having spotify issue.
its says
"spotdl: error: unrecognized arguments: -s: (music link)"
I've installed pip youtubedl,spotdl, every pip I needed.
I'm making this bot for my discord server.
Please help me.
I've learned this from this Youtube link. In this tutorial, bot was working fine. But not mine. What should I do now?
import os
import shutil
from os import system
import discord
import youtube_dl
from discord.ext import commands
from discord.utils import get
TOKEN = 'TOKEN'
BOT_PREFIX = '.'
bot = commands.Bot(command_prefix=BOT_PREFIX)
#bot.event
async def on_ready():
print("Logged in as: " + bot.user.name + "\n")
#bot.command(pass_context=True, aliases=['j', 'joi'])
async def join(ctx):
global voice
channel = ctx.message.author.voice.channel
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
await voice.disconnect()
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
print(f"The bot has connected to {channel}\n")
await ctx.send(f"Joined {channel}")
#bot.command(pass_context=True, aliases=['l', 'lea'])
async def leave(ctx):
channel = ctx.message.author.voice.channel
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.disconnect()
print(f"The bot has left {channel}")
await ctx.send(f"Left {channel}")
else:
print("Bot was told to leave voice channel, but was not in one")
await ctx.send("Don't think I am in a voice channel")
#bot.command(pass_context=True, aliases=['p', 'pla'])
async def play(ctx, url: str):
def check_queue():
Queue_infile = os.path.isdir("./Queue")
if Queue_infile is True:
DIR = os.path.abspath(os.path.realpath("Queue"))
length = len(os.listdir(DIR))
still_q = length - 1
try:
first_file = os.listdir(DIR)[0]
except:
print("No more queued song(s)\n")
queues.clear()
return
main_location = os.path.dirname(os.path.realpath(__file__))
song_path = os.path.abspath(os.path.realpath("Queue") + "\\" + first_file)
if length != 0:
print("Song done, playing next queued\n")
print(f"Songs still in queue: {still_q}")
song_there = os.path.isfile("song.mp3")
if song_there:
os.remove("song.mp3")
shutil.move(song_path, main_location)
for file in os.listdir("./"):
if file.endswith(".mp3"):
os.rename(file, 'song.mp3')
voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
voice.source = discord.PCMVolumeTransformer(voice.source)
voice.source.volume = 100.00
else:
queues.clear()
return
else:
queues.clear()
print("No songs were queued before the ending of the last song\n")
song_there = os.path.isfile("song.mp3")
try:
if song_there:
os.remove("song.mp3")
queues.clear()
print("Removed old song file")
except PermissionError:
print("Trying to delete song file, but it's being played")
await ctx.send("ERROR: Music playing")
return
Queue_infile = os.path.isdir("./Queue")
try:
Queue_folder = "./Queue"
if Queue_infile is True:
print("Removed old Queue Folder")
shutil.rmtree(Queue_folder)
except:
print("No old Queue folder")
await ctx.send("Getting everything ready now")
voice = get(bot.voice_clients, guild=ctx.guild)
ydl_opts = {
'format': 'bestaudio/best',
'quiet': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
try:
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
print("Downloading audio now\n")
ydl.download([url])
except:
print("FALLBACK: youtube-dl does not support this URL, using Spotify (This is normal if Spotify URL)")
c_path = os.path.dirname(os.path.realpath(__file__))
system("spotdl -f " + '"' + c_path + '"' + " -s " + url)
for file in os.listdir("./"):
if file.endswith(".mp3"):
name = file
print(f"Renamed File: {file}\n")
os.rename(file, "song.mp3")
voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
voice.source = discord.PCMVolumeTransformer(voice.source)
voice.source.volume = 0.07
nname = name.rsplit("-", 2)
await ctx.send(f"Playing: {nname[0]}")
print("playing\n")
#bot.command(pass_context=True, aliases=['pa', 'pau'])
async def pause(ctx):
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_playing():
print("Music paused")
voice.pause()
await ctx.send("Music paused")
else:
print("Music not playing failed pause")
await ctx.send("Music not playing failed pause")
#bot.command(pass_context=True, aliases=['r', 'res'])
async def resume(ctx):
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_paused():
print("Resumed music")
voice.resume()
await ctx.send("Resumed music")
else:
print("Music is not paused")
await ctx.send("Music is not paused")
#bot.command(pass_context=True, aliases=['s', 'sto'])
async def stop(ctx):
voice = get(bot.voice_clients, guild=ctx.guild)
queues.clear()
queue_infile = os.path.isdir("./Queue")
if queue_infile is True:
shutil.rmtree("./Queue")
if voice and voice.is_playing():
print("Music stopped")
voice.stop()
await ctx.send("Music stopped")
else:
print("No music playing failed to stop")
await ctx.send("No music playing failed to stop")
queues = {}
#bot.command(pass_context=True, aliases=['q', 'que'])
async def queue(ctx, url: str):
Queue_infile = os.path.isdir("./Queue")
if Queue_infile is False:
os.mkdir("Queue")
DIR = os.path.abspath(os.path.realpath("Queue"))
q_num = len(os.listdir(DIR))
q_num += 1
add_queue = True
while add_queue:
if q_num in queues:
q_num += 1
else:
add_queue = False
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',
}],
}
try:
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
print("Downloading audio now\n")
ydl.download([url])
except:
print("FALLBACK: youtube-dl does not support this URL, using Spotify (This is normal if Spotify URL)")
q_path = os.path.abspath(os.path.realpath("Queue"))
system(f"spotdl -ff song{q_num} -f " + '"' + q_path + '"' + " -s " + url)
await ctx.send("Adding song " + str(q_num) + " to the queue")
print("Song added to queue\n")
#bot.command(pass_context=True, aliases=['n', 'nex'])
async def next(ctx):
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_playing():
print("Playing Next Song")
voice.stop()
await ctx.send("Next Song")
else:
print("No music playing")
await ctx.send("No music playing failed")
bot.run('TOKEN')
Hello Md Sadman Muhtasim Billah!
Well, it seems like the problem is actually in the URL you're submitting, as it don't recognize the '-s' argument, not the parameter itself.
So you should probably try the same URL he uses in the YouTube video you sent, to test it. Or try other links.
I couldn't find a flaw in the code, and it really is the same used in the YT tutorial.
Hope I helped. :)
I am in the process of making a discord.py music bot (my first) and am wondering how to make a queue. I'm guessing that it has something to do with the asyncio command (import asyncio) but I really don't know.
from discord.ext import commands
from discord.utils import get
import asyncio
import youtube_dl
import os
bot = commands.Bot(command_prefix='>')
bot.remove_command('help')
#bot.event
async def on_ready():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=">help"))
print("Bot is online! Logged in as: " + bot.user.name + "\n")
#bot.command(pass_context=True)
async def ping(ctx):
await ctx.send(f'**Pong!** Latency: {round(bot.latency * 1000)}ms')
#bot.command(pass_context=True, aliases=['j'])
async def join(ctx):
channel = ctx.message.author.voice.channel
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
await voice.disconnect()
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
#bot.command(pass_context=True, aliases=['l'])
async def leave(ctx):
channel = ctx.message.author.voice.channel
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.disconnect()
else:
print("Bot was told to leave voice channel, but was not in one.")
await ctx.send("OneBeat is not connected to a voice channel. Connect OneBeat to a voice channel before using this command.")
#bot.command(pass_context=True, aliases=['p'])
async def play(ctx, url: str):
channel = ctx.message.author.voice.channel
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
await voice.disconnect()
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
song_there = os.path.isfile("song.mp3")
try:
if song_there:
os.remove("song.mp3")
print("Removed old song file.")
except PermissionError:
print("Trying to delete song file, but it's being played")
await ctx.send("Error: Music is already playing (Queue feature coming soon).")
return
await ctx.send("One second...")
voice = get(bot.voice_clients, guild=ctx.guild)
ydl_opts = {
'format': 'bestaudio/best',
'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
print(f"Renamed File: {file}\n")
os.rename(file, "song.mp3")
voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: print("Song done!"))
voice.source = discord.PCMVolumeTransformer(voice.source)
voice.source.volume = 0.5
nname = name.rsplit("-", 2)
await ctx.send(f"Now playing: {nname[0]}")
print("Playing\n")
bot.run('token')
Not really! I have no idea how to use asyncio and I still managed to make queues. My way of doing it is to have a json file that contains dictionaries and lists. Which looks something like this:
{
"queueskey": [
{
"channelid": [],
"queue": [],
"status": []
},
{
"channelid": [],
"queue": [],
"status": []
},
{
"channelid": [],
"queue": [],
"status": []
}
]
}
Something like that repeating over and over again. You can also have extra info stored as well with that. Though it took me quite some time to debug and make the thing work, I'd say this is one of the simplest ways of doing it.
I'm developing a discord bot that can find spotify playlists and queue the tracks' youtube counterparts. I have a loop running that uses a list of tracknames to search for a video on youtube, it then grabs the top result and sends to an asynchronous function that plays it. However, whilst the bot is in this loop it does not accept other commands. Can I make this run concurrently with other commands? The following is all the code of my application
from bs4 import BeautifulSoup
import urllib.request
import os
import requests
import base64
import json
import time
import discord
import shutil
from discord.utils import get
from discord import FFmpegPCMAudio
import youtube_dl
import asyncio
from asgiref.sync import async_to_sync
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
bot = commands.Bot(command_prefix='s- ')
accessToken = ""
clientIDSECRET = os.getenv('SPOTIFY_ID')+':'+os.getenv('SPOTIFY_SECRET')
base64Auth = base64.b64encode(clientIDSECRET.encode("utf-8")).decode('ascii')
trackStrings = []
def pretty_print_POST(req):
print('{}\n{}\r\n{}\r\n\r\n{}'.format(
'-----------START-----------',
req.method + ' ' + req.url,
'\r\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
req.body,
))
#bot.event
async def on_ready():
payload={'grant_type':'client_credentials'}
headers = {'Authorization':f'Basic {base64Auth}'}
req = requests.Request('POST', "https://accounts.spotify.com/api/token", data = payload, headers = headers)
prep = req.prepare()
pretty_print_POST(prep)
s = requests.Session()
response = s.send(prep)
global accessToken
accessToken = json.loads(response.content)["access_token"]
print(accessToken)
#bot.command(pass_context=True, aliases=['sp'])
async def spotlist(ctx, userName, playlistName = "", shuffle=False, limit=100, offset=0):
print(limit)
if limit > 100 or limit < 0:
await ctx.send(f'Limit out of bounds! It needs to be between 0 and 100.')
return
playlistId = ""
headers = {'Authorization':f'Bearer {accessToken}'}
if playlistName == "id":
playlistId = userName #Username assumed to be a playlist id instead
else:
playlists = json.loads(requests.get(f'https://api.spotify.com/v1/users/{userName}/playlists', headers=headers).content)
for playlist in playlists["items"]:
if playlist["name"] == playlistName:
playlistId = playlist["id"]
nextURL = f'https://api.spotify.com/v1/playlists/{playlistId}/tracks?offset={offset}&limit={limit}'
while nextURL != None:
trackResponse = requests.get(nextURL, headers = headers)
tracks = json.loads(trackResponse.content)
if(tracks["total"] <= offset):
await ctx.send(f'Offset (third argument) is too large! Your playlist is {tracks["total"]} long.')
return
for track in tracks["items"]:
trackStrings.append(track["track"]["name"] + " " + track["track"]["artists"][0]["name"])
nextURL = tracks["next"]
if(limit != 100):
break
for trackString in trackStrings:
try:
await play(ctx, await SearchVid(trackString))
except:
print("couldn't find song")
#bot.command(pass_context=True, aliases=['j', 'joi'])
async def join(ctx):
channel = ctx.message.author.voice.channel
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
#bot.command(pass_context=True, aliases=['l', 'lea'])
async def leave(ctx):
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.disconnect()
else:
await ctx.send("Don't think I am in a voice channel")
async def playSong(ctx):
voice = get(bot.voice_clients, guild=ctx.guild)
DIR = os.path.abspath(os.path.realpath("Queue"))
try:
first_file = os.listdir(DIR)[0]
except:
print("No more queued song(s)\n")
return
song_path = os.path.abspath(os.path.realpath("Queue") + "\\" + first_file)
async def func(x):
os.remove(song_path)
await playSong(ctx)
try:
voice.play(discord.FFmpegPCMAudio(song_path), after=async_to_sync(func))
await ctx.send(f"playing {first_file}")
voice.source = discord.PCMVolumeTransformer(voice.source)
voice.source.volume = 0.07
except:
print("song already playing")
still_q = len(os.listdir(DIR))
print(f"Songs still in queue: {still_q}")
#bot.command(pass_context=True, aliases=['p', 'pla'])
async def play(ctx, url: str = ""):
await join(ctx)
Queue_infile = os.path.isdir("./Queue")
if Queue_infile is True:
DIR = os.path.abspath(os.path.realpath("Queue"))
try:
_ = os.listdir(DIR)[0]
except:
print("No more queued song(s)\n")
await queue(ctx, url)
await playSong(ctx)
else:
await queue(ctx, url)
await playSong(ctx)
else:
return
#bot.command(pass_context=True, aliases=['s'])
async def skip(ctx):
await stop(ctx)
#bot.command(pass_context=True, aliases=['pa', 'pau'])
async def pause(ctx):
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_playing():
print("Music paused")
voice.pause()
await ctx.send("Music paused")
else:
print("Music not playing failed pause")
await ctx.send("Music not playing failed pause")
#bot.command(pass_context=True, aliases=['r', 'res'])
async def resume(ctx):
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_paused():
print("Resumed music")
voice.resume()
await ctx.send("Resumed music")
else:
print("Music is not paused")
await ctx.send("Music is not paused")
async def stop(ctx):
voice = get(bot.voice_clients, guild=ctx.guild)
if voice and voice.is_playing():
voice.stop()
else:
print("No music playing failed to stop")
async def SearchVid(textToSearch):
print(textToSearch)
query = urllib.parse.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib.request.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}):
if not vid['href'].startswith("https://googleads.g.doubleclick.net/"):
return 'https://www.youtube.com' + vid['href']
async def queue(ctx, url: str):
Queue_infile = os.path.isdir("./Queue")
if Queue_infile is False:
os.mkdir("Queue")
DIR = os.path.abspath(os.path.realpath("Queue"))
q_num = len(os.listdir(DIR))
queue_path = os.path.abspath(os.path.realpath("Queue") + f"\\{q_num} %(title)s.%(ext)s")
print(queue_path)
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': queue_path,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
print("Downloading audio now\n")
print(url)
ydl.download([url])
name = os.listdir(DIR)[-1]
await ctx.send("Adding song " + str(name) + " to the queue")
print("Song added to queue\n")
bot.run(TOKEN)
I would definitely suggest using the module threading. I do not currently have enough time to read your code and put it in, though I might edit this answer later.
Refer to:
https://docs.python.org/3/library/threading.html
Threading allows you to run multiple functions at once.
You're using blocking libraries. Discord.py is a asynchronous library and you need to use things that don't block your code. In Frequently Asked Questions you can see a example using requests library, that's blocking and you should use aiohttp to make asynchronous requests instead.