Unknown Message Already playing audio. When I added to my code cogs it a bit broken him. Before I don't have any error, but now when I calling some command it calls twice. Also I'm getting error like Unknown Message, Already playing audio. etc. (twice) Also I pinned some tracebacks in the image. I'm new in discord.py so hope someone will help me, thank you !
main.py
import discord
import os
from discord.ext import commands
from cogs import embed_command, music
cogs = [embed_command, music]
client = commands.Bot(command_prefix="!", intents=discord.Intents.all())
client.remove_command("help")
# for i in range(len(cogs)):
# cogs[i].setup(client)
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
else:
print(f'Unable to load {filename[:-3]}')
#client.event
async def on_ready():
print("\n\tOnline")
client.run('token')
in folder cogs: embed_command.py
import discord
import asyncio
from discord.ext import commands
class Embed(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_message(self, message):
if message.author == self.client.user:
return
await self.client.process_commands(message)
#commands.command()
async def embed(self, ctx):
embed_question = discord.Embed(
title="Enter a title of embed message: ",
description="||This request will be canceled in 10 seconds!||"
)
embed1 = await ctx.send(embed=embed_question)
try:
msg = await self.client.wait_for("message", check=lambda message: message.author == ctx.author, timeout=10)
msg_color = await self.client.wait_for("message", check=lambda message: message.author == ctx.author,
timeout=10)
r = msg_color.content.split(",", 3)[0]
g = msg_color.content.split(",", 3)[1]
b = msg_color.content.split(",", 3)[2]
embed_question_answer = discord.Embed(
title=msg.content.split("/", 3)[0],
description=msg.content.split("/", 3)[1],
color=discord.Color.from_rgb(int(r), int(g), int(b))
)
# embed_question_answer.add_field(name=msg.content.split("/", 3)[2], value=msg.content.split("/", 3)[3],
# inline=False)
await ctx.send(embed=embed_question_answer)
await msg.delete()
await ctx.message.delete()
await msg_color.delete()
await embed1.delete()
except asyncio.TimeoutError:
timeout_embed = discord.Embed(
title="",
description="***Отмена операции из-за долгого ожидания.***",
color=0x2f3136
)
await ctx.send(embed=timeout_embed, delete_after=5)
await embed1.delete()
await ctx.message.delete()
#commands.command()
async def clear(self, ctx, amount=5):
await ctx.message.delete()
await ctx.channel.purge(limit=amount)
embed_answer = discord.Embed(
title="",
description=f"***{amount} сообщений(-я, -е) было удалено.***",
color=0x2f3136
)
await ctx.send(embed=embed_answer, delete_after=5)
def setup(client):
client.add_cog(Embed(client))
in folder cogs: music.py:
import discord
from discord.ext import commands
import youtube_dl
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("Вы не находитесь в голосовом канале !")
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):
if ctx.author.voice is None:
await ctx.send("Вы не находитесь в голосовом канале !")
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)
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 pause(self, ctx):
ctx.voice_client.pause()
await ctx.send("Приастоновлено.")
#commands.command()
async def resume(self, ctx):
ctx.voice_client.resume()
await ctx.send("Возабновлено.")
def setup(client):
client.add_cog(Music(client))
add an exception so if someone tries command twice it will send them error.
try this:
#commands.command()
async def play(self, ctx, url):
try:
if ctx.author.voice is None:
await ctx.send("Вы не находитесь в голосовом канале !")
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)
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)
except discord.ClientException:
await ctx.send("Already Playing Song")
Related
So basically I have this problem, any command that I type does not work. There are no errors, and everything else is working fine. It's just that for some reasons #bot.command() isn't working, and that is kind of annoying.
import discord
from discord.utils import get
from discord.ext import commands
import time
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix = '$', intents=intents)
TOKEN = 'hi'
ROLE = 'hi'
db1 = [hi, hi]
#bot.command()
async def test(ctx, arg):
await ctx.send(arg)
await bot.process_commands(arg)
#bot.event
async def on_member_join(member):
role = get(member.guild.roles, name=ROLE)
await member.add_roles(role)
await member.send('hi')
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="hi", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="hi", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_member_remove(member):
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_invite_create(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been created, {}, by <#{}> on {}".format(str(invite.url), str(invite.inviter.id), str(invite.created_at)))
#bot.event
async def on_invite_delete(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been deleted by{}".format(str(invite.inviter.id)))
#bot.event
async def on_member_ban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Ban", description="Ban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_member_unban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Unban", description="Unban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_ready():
print(f'{bot.user} succesfully logged in')
return
#bot.event
async def on_message(message):
if message.content.startswith('purge requested by'):
time.sleep(1)
await message.delete()
if message.author == bot:
return
if message.content == 'hi':
await message.channel.send('hi')
if message.content.startswith('binvites'):
totalInvites = 0
for i in await message.guild.invites():
if i.inviter == message.author:
totalInvites += i.uses
await message.channel.send(f"You have invited {totalInvites} member{'' if totalInvites == 1 else 's'} to the Central Trade server")
if message.content == 'bpurge':
if message.author.id in db1:
await message.channel.purge(limit=10)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
else:
return
if message.content == 'block':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = False
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Lock", description="Channel lock request by <#{}>".format(str(message.author.id)), color= 0x00FFFF)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'bunlock':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = True
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Unlock", description="Channel unlock request by <#{}>".format(str(message.author.id)), color=0xC0C0C0)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'test':
embedVar = discord.Embed(title="test", description="test", color=0x00ff00)
embedVar.add_field(name="test", value="test", inline=False)
embedVar.add_field(name="test", value="test", inline=False)
await message.channel.send(embed=embedVar)
if message.content == 'bpurges':
if message.author.id in db1:
await message.channel.purge(limit=10000)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
embedVar = discord.Embed(title="Purge", description="Purge requested by<#{}>".format(str(message.author.id)))
await message.channel.send(embed=embedVar)
time.sleep(1)
await message.channel.delete()
bot.run(TOKEN)
Anyone has an idea why it's not working ? Also seems like i need to post more details, don't pay attention to this : Roméo et Juliette (Romeo and Juliet) est une tragédie de William Shakespeare.
How would I get a my bot to use /tts in a vc?
Here is the code that I have so far. It is a loop of one word and I want to use tts in the voice channel I am in.
#client.command()
async def start(ctx):
global start_channel
start_channel = ctx.channel.id
reminder.start()
await ctx.send('Bot has Started')
#tasks.loop(minutes=10)
async def reminder():
channel = client.get_channel(int(start_channel))
await channel.send('/tts Honk!')
#client.command()
async def stop(ctx):
reminder.cancel()
await ctx.send('Bot has stopped')
#client.command()
async def join(ctx):
if ctx.author.voice is None:
await ctx.send("You're not in a voice channel")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_channel.move_to(voice_channel)
add tts as = True to allow it use tts commands through discord
#tasks.loop(minutes=10)
async def reminder():
channel = client.get_channel(int(start_channel))
await channel.send('Honk!', tts=True)
I have a debug command for my bot that prints all of the current stacks that are running. Problem is it also prints my bot token. Rather than making it so it doesnt print my token, i'd rather make it so the debug command can only be ran by me.
my program:
import discord
from discord.ext import commands
from discord.ext.commands.core import command
import youtube_dl
import traceback
from tabulate import tabulate
table = [['Song', 'Queued by', 'Duration']]
class music(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def join(self, ctx):
await ctx.send("Hello!", ctx.author)
if ctx.author.voice is None:
await ctx.send("Join a voice channel please.")
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 pause(self, ctx):
await ctx.voice_client.pause()
await ctx.send("Music is paused.")
#commands.command()
async def online(self, ctx):
await ctx.send("The bot is online.")
#commands.command()
async def debug(self,ctx):
await ctx.send("You are: ")
await ctx.send(ctx.author)
await ctx.send("You are in the channel:")
if ctx.author.voice:
await ctx.send(ctx.author.voice.channel)
else:
await ctx.send("None")
await ctx.send("Stack: ")
for line in traceback.format_stack():
await ctx.send(line.strip())
#commands.command()
async def resume(self, ctx):
await ctx.voice_client.resume()
await ctx.send("Music has been resumed.")
#commands.command()
async def queue(self, ctx):
await ctx.send(tabulate(table, headers='firstrow'))
def setup(client):
client.add_cog(music(client))
You can for example return when the user's id that used the command is not yours:
#commands.command()
async def debug(self, ctx):
if ctx.author.id != "your id":
return
# The rest of your debug command
So I trying to create my own music bot for my own server with Python since Rhythm and Groovy unavailable, but I can't play it with YouTube URL. Do anyone have the solution?
#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)
if 'entries' in info:
url2 = info["entries"][0]["formats"][0]['url']
elif 'formats' in info:
url2 = info["entries"][0]["formats"][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
import asyncio
import os
import discord
import youtube_dl
from discord.ext import commands
# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambda: ''
ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues
sometimes
}
ffmpeg_options = {
'options': '-vn'
}
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, volume=1.0):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
self.url = data.get('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)
bot = commands.Bot(command_prefix = '!')
#bot.event
async def on_ready():
await bot.change_presence(activity = discord.Activity(type =
discord.ActivityType.listening, name = "your favourite song :)"), status =
discord.Status.idle)
print('bot ready')
#bot.command(description="joins a voice channel")
async def join(ctx):
if ctx.author.voice is None or ctx.author.voice.channel is None:
return await ctx.send('You need to be in a voice channel to use this
command!')
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
vc = await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
vc = ctx.voice_client
async def on_ready(self):
for guild in self.client.guilds:
self.song_queue[guild.id] = []
async def check_queue(ctx):
if len(ctx.song_queue[ctx.guild.id]) > 0:
ctx.voice_client.stop()
await ctx.play(ctx.song_queue[ctx.guild.id][0])
#bot.command(description="streams music", aliases = ['pl','p'])
async def play(ctx,*, url):
async with ctx.typing():
player = await YTDLSource.from_url(url, loop= bot.loop, stream=True)
ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e)
if e else None)
await ctx.send('Now playing: **{}**'.format(player.title))
song_queue = check_queue(ctx)
song_queue[ctx.guild.id].append(player)
#bot.command(description="stops and disconnects the bot from voice")
async def leave(ctx):
await ctx.voice_client.disconnect()
#play.before_invoke
async def ensure_voice(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()
bot.run('TOKEN')
Try this code; works only with url. Also, I have only the join, play and leave command, it's just a very basic music bot, and it does not queue either.
#commands.command(name='play')
async def _play(self, ctx: commands.Context, *, search: str):
"""Plays a song.
If there are songs in the queue, this will be queued until the
other songs finished playing.
This command automatically searches from various sites if no URL is provided.
"""
if not ctx.voice_state.voice:
await ctx.invoke(self._join)
async with ctx.typing():
try:
source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop)
except YTDLError as e:
await ctx.send('An error occurred while processing this request: {}'.format(str(e)))
else:
song = Song(source)
await ctx.voice_state.songs.put(song)
await ctx.send('Enqueued {}'.format(str(source)))
The above code has been taken from here. As this is a common question I thought that using pre-tested code would be the correct option.
I had make a discord bot command that plays music .Also it does everything fine and it is also playing music .The problem is that whenever i command it download the music on my system.I have not much space to remain those mp3 on my system .So, what can i do with this.Here is the code given below .Hope you'll help.(I have also downloaded all the modules including ffmpeg).
#client.command(aliases=["p"])
async def play(ctx, *, query):
try:
voiceChannel = discord.utils.get(ctx.guild.voice_channels, name=str(ctx.message.author.voice.channel))
await voiceChannel.connect()
await ctx.send("Joined " + str(ctx.message.author.voice.channel) + " voice channel!:white_check_mark:")
except AttributeError:
await ctx.send(ctx.message.author.mention + " is not in any voice channel :negative_squared_cross_mark:")
return
except Exception as e:
print(e)
url = None
if len(query) == 0:
await ctx.send(
ctx.message.author.mention + "you need to provide a youtube video link or any query with the play command :negative_squared_cross_mark:")
return
elif query.startswith("https://www.youtube.com/watch?v="):
url = query
else:
s = gs.search("https://www.youtube.com/results?search_query=" + query.replace(" ", "+"), "com", "en", num=10,
stop=10, pause=2.0)
for i in s:
if i.startswith("https://www.youtube.com/watch?v="):
url = i
break
if url == None:
await ctx.send(ctx.message.author.mention + " some error is caused :negative_squared_cross_mark:")
return
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
yt = YouTube(str(url))
yt_embed = discord.Embed(title=yt.title + ":musical_note:", description=yt.description, color=discord.Colour.red())
yt_embed.set_thumbnail(url=yt.thumbnail_url)
yt_embed.add_field(name="Author: ", value=yt.author + ":musical_score: ", inline=False)
yt_embed.add_field(name="Duration: ", value=str(yt.length) + " seconds :clock3: ", inline=False)
yt_embed.add_field(name="Publish date: ", value=str(yt.publish_date) + ":calendar_spiral:", inline=False)
yt_embed.add_field(name="Rating: ", value=str(yt.rating) + ":star2:", inline=False)
yt_embed.add_field(name="Views: ", value=str(yt.views) + ":eyes:", inline=False)
t = yt.streams.filter(only_audio=True)
t[0].download(".\songs")
try:
print(".\songs\\" + yt.title + ".mp4")
voice.play(discord.FFmpegPCMAudio(".\songs\\" + yt.title + ".mp4"))
await ctx.send("Playing " + yt.title + " :loud_sound:")
await ctx.send(embed=yt_embed)
except Exception as e:
print(e)
await ctx.send(ctx.message.author.mention + " Alena already playing audio :negative_squared_cross_mark:")
await ctx.send(
"Use stop command to stop the currently playing song and leave command to make Alena exit the current voice channel")
return
#client.command(aliases=["disconnect", "exit"])
async def leave(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_connected():
await voice.disconnect()
await ctx.send("Disconnected :wave:")
else:
await ctx.send("The bot is not connected to a voice channel. :negative_squared_cross_mark:")
#client.command()
async def pause(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.pause()
await ctx.send("Paused :pause_button:")
else:
await ctx.send("Currently no audio is playing. :negative_squared_cross_mark:")
#client.command()
async def resume(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_paused():
voice.resume()
await ctx.send("Resumed :play_pause: ")
else:
await ctx.send("The audio is not paused. :negative_squared_cross_mark:")
#client.command()
async def stop(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
voice.stop()
await ctx.send("Stopped playing :octagonal_sign: ")
Create a folder named cogs in your project and then add a file named music.py to the cogs folder. Put all this code below in that music.py file:
import asyncio
import discord
import youtube_dl
from discord.ext import commands
# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambda: ''
ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes
}
ffmpeg_options = {
'options': '-vn'
}
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, volume=0.5):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
self.url = data.get('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(description="joins a voice channel")
async def join(self, ctx):
if ctx.author.voice is None or ctx.author.voice.channel is None:
return await ctx.send('You need to be in a voice channel to use this command!')
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
vc = await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
vc = ctx.voice_client
#commands.command(description="streams music")
async def play(self, ctx, *, url):
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send('Now playing: {}'.format(player.title))
#commands.command(description="pauses music")
async def pause(self, ctx):
ctx.voice_client.pause()
#commands.command(description="resumes music")
async def resume(self, ctx):
ctx.voice_client.resume()
#commands.command(description="stops and disconnects the bot from voice")
async def leave(self, ctx):
await ctx.voice_client.disconnect()
#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(bot):
bot.add_cog(Music(bot))
Then, in your on_ready() method in your main .py file, add this:
#bot.event
async def on_ready():
bot.load_extension("cogs.music")
Modify the code to whatever you would like the commands to print. Please verify this answer if it works.