How to check if discord bot is in channel? - python

I kinda made this working music bot code, it join vc and play the song. But when its in voice it wont play another one, i need to disconnect him. I want that he play next song even if he is joined. How to do it?
code(part where i want the thing):
#bot.command()
async def hraj(ctx, url):
if not ctx.message.author.voice:
await ctx.send("Musíš být ve voicu ty pepego!")
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=bot.loop)
voice_channel.play(player, after=lambda e: print("Error. %s" %e if e else None))
e = discord.Embed(title="Právě hraje:", description=f"[{player.title}]({url})", color=0x0091ff)
e.set_footer(text="Lets go jdem vibovat <333")
await ctx.send(embed=e)

You could use
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice == None:
channel = ctx.message.author.voice.channel
This works because discord.utils.get(client.voice_clients, guild=ctx.guild) returns None if your bot isn't in a voice channel.
So your code would be:
#bot.command()
async def hraj(ctx, url):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice == None:
channel = ctx.message.author.voice.channel
else:
await ctx.send('Musíš být ve voicu' ty pepego)
await channel.connect()
server = ctx.message.guild
voice_channel = server.voice_client
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=bot.loop)
voice_channel.play(player, after=lambda e: print("Error. %s" %e if e else None))
e = discord.Embed(title="Právě hraje:", description=f"[{player.title}]({url})", color=0x0091ff)
e.set_footer(text="Lets go jdem vibovat <333")
await ctx.send(embed=e)
Your question wasn't very clear btw.

Related

How does coding the pause and resume commands work when coding a discord bot?

I have tried to code a music bot of sorts, and it the code I put for the pause command doesn't work. I don't know about the resume command, since I'd have to first get the pause command working.
Here is the code:
#client.command(pass_context = True)
async def join(ctx):
if (ctx.author.voice):
vc = ctx.message.author.voice.channel
voice = await vc.connect()
source = FFmpegPCMAudio('Forest Battle - Battle music.mp3')
player = voice.play(source)
else:
await ctx.send("You need to be in a voice channel before using this command!")
#client.command(pass_context = True)
async def leave(ctx):
if (ctx.voice_client):
await ctx.guild.voice_client.disconnect()
await ctx.send("`RSS Dnd Bot has left the voice channel!`")
else:
await ctx.send("`RSS Dnd Bot isn't currently in any voice channel!`")
#client.command(pass_context = True)
async def pause(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.pause
else:
await ctx.send("`Nothing is currently playing right now!`")
#client.command(pass_context = True)
async def resume(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_paused():
voice.resume()
else:
await ctx.send("`Nothing is currently paused right now!`")
This is my pause command:
#client.command(name='pause', description="pauses music")
async def pause_(ctx):
"""Pause the currently playing song."""
vc = ctx.voice_client
if not vc or not vc.is_playing():
embed = discord.Embed(title="", description="I am currently not playing anything", color=discord.Color.green())
return await ctx.send(embed=embed)
elif vc.is_paused():
return
vc.pause()
await ctx.send("Paused ⏸️")
This is my resume command:
#client.command(name='resume', description="resumes music")
async def resume_(ctx):
"""Resume the currently paused song."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
elif not vc.is_paused():
return
vc.resume()
await ctx.send("Resuming ⏯️")

modmail system discord.py no response to reaction

so i was making a discord bot and made a modmail system and got this error. can someone plz help and tell me where i am going wrong i searched many similar errors but didnt find the answer.
bot:
import random
import os
import sys
import asyncio
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='-', intents=intents)
client.remove_command("help")
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.idle, activity=discord.Game('Do -help'))
print('functioning...')
#client.event
async def on_member_join(member):
print(f'{member} has joined the server.')
await member.create_dm()
await member.dm_channel.send(f'Hi {member.mention}, welcome to my Discord server!')
#client.event
async def on_member_remove(member):
print(f'{member} has left the server.')
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension(f'cogs.{filename[:-3]}')
#client.command(brief="Load", help="Loading cogs")
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
#client.command(brief="Unload", help="Unloading cogs")
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
#client.command(brief="Ping", help="The time it takes for a small data set to be transmitted from your device to a server on the Internet and back to your device again.")
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency*1000)}ms')
#client.command(aliases=['test','8ball', 'future'], brief="8ball", help="A little fun game.")
async def _8ball(ctx, *,question):
responses=[ "It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."]
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')
#client.command(aliases=['purge','clean'], brief="Purge", help="Clears a fixed number of messahes.")
#commands.has_permissions(manage_messages=True)
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
#client.command(brief="Kick", help="Kicks a person out of the guild.")
#commands.has_permissions(manage_messages=True)
async def kick(ctx, member:discord.Member, *, reason=None):
message = f"You have been kicked from {ctx.guild.name}, reason: {reason}"
await member.send(message)
await member.kick(reason=reason)
await ctx.send(f'Kicked {member.mention}')
#client.command(brief="Ban", help="Bans a person in the guild.")
#commands.has_permissions(manage_messages=True)
async def ban(ctx, member:discord.Member, *, reason=None):
message = f"You have been banned from {ctx.guild.name}, reason: {reason}"
await member.send(message)
await member.ban(reason=reason)
await ctx.send(f'Banned {member.mention}')
#client.command(brief="Unban", help="Unbans a banned person in the guild.")
#commands.has_permissions(manage_messages=True)
async def unban(ctx, *, user=None):
try:
user = await commands.converter.UserConverter().convert(ctx, user)
except:
await ctx.send("Error: user could not be found!")
return
try:
bans = tuple(ban_entry.user for ban_entry in await ctx.guild.bans())
if user in bans:
await ctx.guild.unban(user, reason="Responsible moderator: "+ str(ctx.author))
else:
await ctx.send("User not banned!")
return
except discord.Forbidden:
await ctx.send("I do not have permission to unban!")
return
except:
await ctx.send("Unbanning failed!")
return
await ctx.send(f"Successfully unbanned {user.mention}!")
class DurationConverter(commands.Converter):
async def convert(self, ctx, argument):
amount=argument[:-1]
unit=argument[-1]
if amount.isdigit() and unit in ['s','m','h','d']:
return(int(amount),unit)
raise commands.BadArgument(message="Not a valid duration")
#client.command(brief="Tempban", help="Temporarily bans a person in the guild.")
#commands.has_permissions(manage_messages=True)
async def tempban(ctx, member: commands.MemberConverter, duration: DurationConverter):
multiplier={'s':1, 'm':60, 'h':3600, 'd':86400}
amount, unit= duration
message = f"You have been banned from {ctx.guild.name}, for {amount}{unit}"
await member.send(message)
await ctx.guild.ban(member)
await ctx.send(f'{member.mention} has been banned for {amount}{unit}')
await asyncio.sleep(amount*multiplier[unit])
await ctx.guild.unban(member)
#client.command(brief="Tempmute", help="Temporarily mutes a person in the guild.")
#commands.has_permissions(manage_messages=True)
async def tempmute(ctx, member: discord.Member, duration: DurationConverter, reason=None):
multiplier = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
amount, unit = duration
guild = ctx.guild
muteRole = discord.utils.get(guild.roles, name="Muted")
await member.add_roles(muteRole, reason=reason)
await ctx.send(f"{member.mention} has been muted in {ctx.guild} for {amount}{unit}")
await member.send(f"You have been muted in {ctx.guild} for {amount}{unit}")
await asyncio.sleep(amount*multiplier[unit])
await member.remove_roles(muteRole, reason=reason)
await ctx.send(f"{member.mention} has been unmuted in {ctx.guild} ")
await member.send(f"You have been unmuted in {ctx.guild} ")
def restart_bot():
os.execv(sys.executable, ['python'] + sys.argv)
#client.command(name= 'restart', brief="Restart", help="Restarts the bot.")
async def restart(ctx):
await ctx.send("Restarting bot...")
restart_bot()
#client.command( brief="Connects", help="Connects the bot.")
async def connect(self):
print(" bot connected")
#client.command(brief="Disconnects", help="Disconnects the bot.")
async def disconnect(self):
print("bot disconnected")
#client.command(brief="Mute", help="Mutes a person in the guild.")
#commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guild
muteRole = discord.utils.get(guild.roles, name="Muted")
if not muteRole:
await ctx.send("No Mute Role found! Creating one now...")
muteRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(muteRole, speak=False, send_messages=False, read_messages=True,
read_message_history=True)
await member.add_roles(muteRole, reason=reason)
await ctx.send(f"{member.mention} has been muted in {ctx.guild} | Reason: {reason}")
await member.send(f"You have been muted in {ctx.guild} | Reason: {reason}")
#client.command(brief="Unmute", help="Unmutes a muted person in the guild.")
#commands.has_permissions(manage_messages=True)
async def unmute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guild
muteRole = discord.utils.get(guild.roles, name="Muted")
await member.remove_roles(muteRole, reason=reason)
await ctx.send(f"{member.mention} has been unmuted in {ctx.guild}")
await member.send(f"You have been unmuted in {ctx.guild}")
#client.command(brief="Slowmode", help="Enables a rate limit per message.")
#commands.has_permissions(manage_messages=True)
async def slowmode(ctx, time:int):
if (not ctx.author.guild_permissions.manage_messages):
await ctx.send('Cannot run command! Requires: ``Manage Messages``')
return
if time == 0:
await ctx.send('Slowmode is currently set to `0`')
await ctx.channel.edit(slowmode_delay = 0)
elif time > 21600:
await ctx.send('You cannot keep the slowmode higher than 6 hours!')
return
else:
await ctx.channel.edit(slowmode_delay = time)
await ctx.send(f"Slowmode has been set to `{time}` seconds!")
#client.command(brief="Prefix", help="Changes the prefix.")
async def setprefix(ctx, prefix):
client.command_prefix = prefix
await ctx.send(f"Prefix changed to ``{prefix}``")
#client.command(brief="Avatar", help="Displays a guild members pfp.")
async def avatar(ctx, member: discord.Member = None):
if member == None:
member = ctx.author
icon_url = member.avatar_url
avatarEmbed = discord.Embed(title=f"{member.name}\'s Avatar", color=0x802BAE)
avatarEmbed.set_image(url=f"{icon_url}")
avatarEmbed.timestamp = ctx.message.created_at
await ctx.send(embed=avatarEmbed)
client.run(token)
modmail:
import discord
import asyncio
from discord.ext.commands import Cog
client = discord.Client()
sent_users = []
class modmail(Cog):
def __init__(self, bot):
self.bot = bot
#Cog.listener()
async def on_message(self,message):
if message.guild: # ensure the channel is a DM
return
if message.author.bot:
return
if message.author == client.user:
return
if message.author.id in sent_users: # Ensure the intial message hasn't been sent before
return
modmail_channel = discord.utils.get(client.get_all_channels(), name="modmail")
embed = discord.Embed(color=0x00FFFF)
embed.set_author(name=f"Modmail System",
icon_url="https://cdn.discordapp.com/icons/690937143522099220/34fbd058360c3d4696848592ff1c5191.webp?size=1024")
embed.add_field(name='Report a member:', value=f"React with 1️⃣ if you want to report a member.")
embed.add_field(name='Report a Staff Member:', value=f"React with 2️⃣ if you want to report a Staff Member.")
embed.add_field(name='Warn Appeal:', value=f"React with 3️⃣ if you would like to appeal a warning.")
embed.add_field(name='Question:',
value=f"React with 4️⃣ if you have a question about our moderation system or the server rules.")
embed.set_footer(text="Modmail")
msg = await message.channel.send(embed=embed)
await msg.add_reaction("1️⃣")
await msg.add_reaction("2️⃣")
await msg.add_reaction("3️⃣")
await msg.add_reaction("4️⃣")
sent_users.append(message.author.id) # add this user to the list of sent users
try:
def check(reaction, user):
return user == message.author and str(reaction.emoji) in ["1️⃣", "2️⃣", "3️⃣", "4️⃣"]
reaction, user = await client.wait_for("reaction_add", timeout=60, check=check)
if str(reaction.emoji) == "1️⃣":
embed = discord.Embed(color=0x00FFFF)
embed.set_author(name=f"Modmail System",
icon_url="https://cdn.discordapp.com/icons/690937143522099220/34fbd058360c3d4696848592ff1c5191.webp?size=1024")
embed.add_field(name='How to Report:',
value="Send the ID of the person you are reporting and attach add a screen shot of them breaking a rule (can be ToS or a server rule).")
embed.set_footer(text="Report a member ")
await message.author.send(embed=embed)
message = await client.wait_for("message", timeout=60, check=lambda
m: m.channel == message.channel and m.author == message.author)
embed = discord.Embed(title=f"{message.content}", color=0x00FFFF)
await modmail_channel.send(embed=embed)
except asyncio.TimeoutError:
await message.channel.send("Reaction timeout!!!")
#Cog.listener()
async def on_ready(self):
print("modmail ready")
def setup(bot):
bot.add_cog(modmail(bot))
logcog:
import discord
import datetime
from datetime import datetime
from discord.ext.commands import Cog
class Example(Cog):
def __init__(self, client):
self.client = client
#Cog.listener()
async def on_ready(self):
print("log ready")
#Cog.listener()
async def on_message(self, message):
if not message.guild:
pass
else:
if not message.content and message.channel:
pass
else:
channel = discord.utils.get(message.guild.channels, name='log')
embed = discord.Embed(title="Message sent", description=message.author, color=message.author.color,
timestamp=datetime.utcnow())
embed.add_field(name="Message Sent", value=message.content, inline=True)
embed.add_field(name="Channel Sent", value=message.channel, inline=True)
await channel.send(embed=embed)
#Cog.listener()
async def on_message_edit(self, before, after):
if len(before.content)==0 and len(after.content)==0 and len(before.channel)==0:
pass
elif not before.guild:
pass
else:
channel = discord.utils.get(before.guild.channels, name='log')
embed = discord.Embed(title="Message edited", description=before.author, color=before.author.color,
timestamp=datetime.utcnow())
embed.add_field(name="Before edit", value=before.content, inline=True)
embed.add_field(name="After edit", value=after.content, inline=True)
embed.add_field(name="Channel Sent", value=before.channel, inline=True)
await channel.send(embed=embed)
#Cog.listener()
async def on_message_delete(self, message):
if not message.content and message.channel:
pass
elif not message.guild:
pass
else:
channel = discord.utils.get(message.guild.channels, name='log')
embed = discord.Embed(title="Message deleted", description=message.author, color=message.author.color,
timestamp=datetime.utcnow())
embed.add_field(name="Deleted Message", value=message.content, inline=True)
embed.add_field(name="The channel is", value=message.channel, inline=True)
await channel.send(embed=embed)
def setup(client):
client.add_cog(Example(client))
so when i run this code i get the reaction message and embed in the dm but when i click on the reaction i get no further out put and after 60s a message comes reaction timeout. I dont get any error message either.
So I finally solved the problem, which stemmed from the intents setup. In my main file I used this code:
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
bot.load_extension("cogs.maincog")
bot.run(token)
You may want to do this slightly differently (like by using client), but the important part is the intents. This is apparently because the privileged intent "members" is required when testing for reactions is direct messages. I replaced the client with the Bot class, so the testing function became:
reaction, user = await self.bot.wait_for("reaction_add", timeout=60, check=check)
As far as I have tested, this should work perfectly well but let me know if you have any problems or want me to link the full code.
Edit: Look at how to enable privileged intents here.

How to make Discord.py music bot automatically play next song in queue

After song finishes, song is popped from the playlist queue, but does not continue playing the next song in queue. So the queue command only shows the song sitting in there. How should I change this to run the next song?
playlist = []
#client.command(name='play', help='Plays music')
async def play(ctx):
voice = ctx.message.guild.voice_client
def is_connected(): # Tests if bot is connected to voice channel
voice_client = discord.utils.get(ctx.bot.voice_clients, guild=ctx.guild)
return voice_client and voice_client.is_connected()
url = ctx.message.content.lstrip('?play')
playlist.append(url.lstrip(' '))
if not ctx.message.author.voice:
await ctx.send("You are not connected to a voice channel")
playlist.pop(0)
return
else:
channel = ctx.message.author.voice.channel
if is_connected():
if voice.is_playing(): # url already added to the playlist, downloads each index
index = len(playlist)-1
player = await YTDLSource.from_url(playlist[index], loop=client.loop)
await ctx.send('**Added:** {} to queue'.format(player.title))
playlist[index] = player.title
else:
server = ctx.message.guild
voice_channel = server.voice_client
async with ctx.typing():
player = await YTDLSource.from_url(playlist[0], loop=client.loop)
voice_channel.play(player, after=lambda e: print('Player error: %s' % e) if e else ctx.send('hi'))
print(player.title)
await ctx.send('**Now playing:** {}'.format(player.title))
playlist[0] = player.title
playlist.pop(0)
else:
await channel.connect()
server = ctx.message.guild
voice_channel = server.voice_client
async with ctx.typing():
player = await YTDLSource.from_url(playlist[0], loop=client.loop)
voice_channel.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
print(player.title)
await ctx.send('**Now playing:** {}'.format(player.title))
playlist[0] = player.title```
await channel.connect()
server = ctx.message.guild
voice_channel = server.voice_client
async with ctx.typing():
player = await YTDLSource.from_url(playlist[0], loop=client.loop)
voice_channel.play(player, after=lambda e: asyncio.run_coroutine_threadsafe(after_play(ctx), client.loop))
print(player.title)
await ctx.send('**Now playing:** {}'.format(player.title))
playlist[0] = player.title
async def after_play(ctx):
playlist.pop(0)
server = ctx.message.guild
voice_channel = server.voice_client
player = await YTDLSource.from_url(playlist[0], loop=client.loop)
voice_channel.play(player, after=lambda e: asyncio.run_coroutine_threadsafe(after_play(ctx), client.loop))
print(player.title)```
For Music related things you have to set up more than things like commands (play, skip, disconnect, etc.).
Kindly look at examples on Music bots and stuff.
I have one but it's old but the logic is what you need. https://github.com/Gaming-Rowdies/cs-music/

Discord Bot Join/Leave

#Bot.command()
async def join(ctx):
if (ctx.author.voice):
channel = ctx.author.voice.channel
await channel.connect()
await ctx.send('Bot joined')
else:
await ctx.send("You must be in a voice channel first so I can join it.")
#Bot.command()
async def leave(
ctx):
if (ctx.voice_client):
await ctx.guild.voice_client.disconnect()
await ctx.send('Bot left')
else:
await ctx.send("I'm not in a voice channel, use the join command to make me join")
I'm using this code for my bot. The bot can join but cannot leave, it ignores commands to leave when they are sent.
This should work:
#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
#Bot.command(description="stops and disconnects the bot from voice")
async def leave(ctx):
if ctx.voice_client is None:
await ctx.send("I'm not in a voice channel, use the join command to make me join")
else:
await ctx.voice_client.disconnect()
await ctx.send('Bot left')

Disconnect the music bot from voice channel

I have this as my music class to make my bot play music
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.music = lavalink.Client(self.bot.user.id)
self.bot.music.add_node("localhost", 7000, 'server-utils', 'eu', 'music-node')
self.bot.add_listener(self.bot.music.voice_update_handler, 'on_socket_response')
self.bot.music.add_event_hook(self.track_hook)
#commands.command(name="music")
async def music(self, ctx, opt, *, arg=None):
if opt == "join":
print(f"music join command worked")
member = discord.utils.find(lambda m: m.id == ctx.author.id, ctx.guild.members)
if member is not None and member.voice is not None:
vc = member.voice.channel
player = self.bot.music.player_manager.create(ctx.guild.id, endpoint=str(ctx.guild.region))
if not player.is_connected:
player.store('channel', ctx.guild.id)
await self.connect_to(ctx.guild.id, str(vc.id))
if opt == "play" and arg is not None:
try:
player = self.bot.music.player_manager.get(ctx.guild.id)
query = f'ytsearch:{arg}'
results = await player.node.get_tracks(query)
tracks = results['tracks'][0:10]
i = 0
query_result = ''
for track in tracks:
i = i + 1
query_result = query_result + f'{i}) {track["info"]["title"]}\n'
embed = discord.Embed()
embed.description = query_result
await ctx.channel.send(embed=embed)
def check(m):
return m.author.id == ctx.author.id
reponse = await self.bot.wait_for('message', check=check)
track = tracks[int(reponse.content)-1]
player.add(requester=ctx.author.id, track=track)
if not player.is_playing:
await player.play()
except Exception as error:
print(error)
if opt == "stop":
try:
player = self.bot.music.player_manager.get(ctx.guild.id)
if player.is_playing:
await player.stop()
except Exception as error:
print(error)
if opt == "leave":
player = self.bot.music.player_manager.get(ctx.guild.id)
if player.is_playing:
await player.stop()
await self.disconnect_from(ctx.guild.id)
async def track_hook(self, event):
if isinstance(event, lavalink.events.QueueEndEvent):
guild_id = int(event.player.guild_id)
await self.connect_to(guild_id, None)
async def connect_to(self, guild_id: int, channel_id: int):
ws = self.bot._connection._get_websocket(guild_id)
await ws.voice_state(str(guild_id), channel_id)
async def disconnect_from(self, guild_id: int):
ws = self.bot._connection.voice_clients
print(ws)
def setup(bot):
bot.add_cog(Music(bot))
Everythink works fine except the part to disconnect from the channel he is connected to... I've tried lots of things and can't figure out how to make it disconnect..
Ps: Here the command doesn't do anything but to print a list where I hoped there would be the bot connect, but it had nothing there
I believe it's because you're passing the guild id as opposed to the voice channels id, for example.
You're in the guild; Hello World with an ID of 12345
You're in the guilds voice channel of; Hello World voice channel which has an id of 6789.
so you're trying to use the guild.id as opposed to the voice channel id. Does this make sense?
Can't you do await ctx.voice_client.disconnect()
if opt == "leave":
player = self.bot.music.player_manager.get(ctx.guild.id)
if player.is_playing:
await player.stop()
await ctx.voice_client.disconnect()
I did a disconnect command on my Discord bot using VoiceClient.disconnect(). I got some trouble with it in my first approach because the connect command generated the VoiceClient object, but disconnect command could not use it since it was a local variable on the other command, so i just made it global and it works
#commands.command()
async def enter(self, ctx):
try:
canal = ctx.author.voice.channel
global voice_client
voice_client = await canal.connect()
except AttributeError:
await ctx.send("Você precisa estar conectado a um canal de voz")
except discord.errors.ClientException:
await ctx.send("Eu já estou conectado ao seu canal de voz")
#commands.command()
async def leave(self, ctx):
try:
await voice_client.disconnect()
except NameError:
await ctx.send("Eu não estou conectado a nenhum canal de voz :worried:")
The full music cog that I coded:
https://github.com/Voz-bonita/Discord-Bot/blob/master/Music%20extension.py

Categories