How to check if bot is connected to a channel? | discord.py

泄露秘密 提交于 2021-01-04 12:27:02

问题


I've decided to try making my discord bot play music, but I've gotten stuck already. Mainly due to the fact I can't find any sources to help with the current version, I've been winging everything from the docs. However, I can't figure out how to check if the bot is connected to a voice channel.

I have tried if not Client.is_connected():, however that didn't work. If there are any updated sources to help me get the basics of discord.py's voice features, please give me a link :) Here is my code so far:

# ----- ATTEMPT AT VOICE COMMANDS ------
#discord.opus.load_opus() - what goes in bracket???

@client.command(name="join", pass_ctx=True)
async def join(ctx):
    #if not is_connected(): - Client.is_connected() not working

    user = ctx.message.author
    vc = user.voice.channel
    await vc.connect()
    await ctx.send(f"Joined **{vc}**")

    #else:
    #    await ctx.send("I'm already connected!")

@client.command(name="disconnect", pass_ctx=True)
async def disconnect(ctx):
    # if not is_connected(): - once again can't work it out
    vc = ctx.message.guild.voice_client # i don't even know how this worked :D
    await vc.disconnect()

    #else:
    #    await ctx.send("I'm not connected to any channels")

@client.command(name="play", pass_ctx=True)
async def play(ctx, songurl=None):
    if not songurl: # this works at least
        await ctx.send("Please specify a song")
        return
    if not is_connected(): # once again, how to check if bot is connected?
        vc = ctx.message.author.voice.channel
        if not vc: # i think this should work
            await ctx.send("You're not in a voice channel!")

        await vc.connect()
    # haven't even worked out anything past this point and it's broken

ps: sorry for just dumping my whole vc section but i don't understand a lot

Really all that matters here is the play command, but I included the others just because (as you can see from my comments) I don't understand LOTS of what is going on. How should I go about this? Are there any good sources for the current version? Thanks in advance.


回答1:


A bot can be connected to voice in multiple guilds at the same time, so you need to get the VoiceClient for the appropriate guild from Client.voice_clients and then check VoiceClient.is_connected:

def is_connected(ctx):
    voice_client = get(ctx.bot.voice_clients, guild=ctx.guild)
    return voice_client and voice_client.is_connected()


来源:https://stackoverflow.com/questions/56718658/how-to-check-if-bot-is-connected-to-a-channel-discord-py

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!