How to check is discord bot is in voice or already connected

Viewed 336

I am building a bot where the bot needs to connect to a voice channel, here is my code:

import discord
from discord.ext import commands
from discord.utils import get

b = commands.Bot(command_prefix=".")

@b.event
async def on_ready():
    print("Bot is logged in")

@b.command(pass_context=True, aliases=['j'])
async def join(ctx):
    channel = ctx.message.author.voice.channel
    voice = get(b.voice_clients, guild=ctx.guild)

    if voice and voice.is_connected():
        await voice.move_to(channel)
        await ctx.send("Moved to the voice channel")

    elif #Check if the user is in the voice channel and the bot is not:
        voice = await channel.connect()
        await ctx.send("Connected to the voice channel")

    elif #Check if the user is in the voice channel
        await ctx.send("**Get in a voice channel**")

    elif #Check if the bot is already in the channel
        await ctx.send("**Already in the channel**")

b.run("stack overflow")

So there's a couple things I want to check before entering the voice channel, I figured out how to connect and to move from different voice channel but am stuck there, I'm new to python so if my code can be simplified any suggestions would be much appreciated.

1 Answers
@b.command(aliases=['j'])
async def join(ctx):
    bot_voice = ctx.guild.voice_client
    author_voice = ctx.author.voice

    if bot_voice and bot_voice.is_connected():
        await voice.move_to(author_voice.channel)
        await ctx.send("Moved to the voice channel")

    elif author_voice and not bot_voice: # Author connected but bot not connected
        voice = await author_voice.channel.connect()
        await ctx.send("Connected to the voice channel")

    elif not author_voice: # Author not connected
        await ctx.send("**Get in a voice channel**")

    elif ctx.bot.user in author_voice.channel.members # Bot and Author both connected
        await ctx.send("**Already in the channel**")

btw pls don't name your bot b, it's bad practice

Related