kevinvi8
kevinvi8

Reputation: 321

Discord Bot won't tell someone to join a voice channel, instead it just throws an error. Other parts work totally fine

I've been working on this function for my Discord bot for quite a while and finally got most of it up and running, but I am running into an issue for my "Connect to a voice channel" warning. The segment of code is as follows:

 @commands.command(name="play", help="Plays a selected song from youtube")
    async def p(self, ctx, *args):
        query = " ".join(args)
        
        voice_channel = ctx.message.author.voice.channel
        if voice_channel is None:
            #you need to be connected so that the bot knows where to go
            await message.channel.send("Connect to a voice channel!")
        else:
            song = self.search_yt(query)
            if type(song) == type(True):
                await ctx.send("Could not download the song. Incorrect format try another keyword. This could be due to playlist or a livestream format.")
            else:
                await ctx.send("Song added to the queue")
                self.music_queue.append([song, voice_channel])

Now this all seems to be working pretty well except for the "if voice_channel is None" portion. An error keeps getting thrown saying "NoneType' object has no attribute 'channel'".

I'm sure this is fairly simple and I understand the gist of the problem (obviously not the first time I've seen 'NoneType' object errors, but I just can't seem to figure out what I need to change here.

As I said previously, As long as I am in a voice channel everything works perfectly. The bot connects, downloads, & plays the music.

Upvotes: 1

Views: 666

Answers (2)

Eli Harold
Eli Harold

Reputation: 2301

You need to use try: like so:

@commands.command(name="play", help="Plays a selected song from youtube")
    async def p(self, ctx, *args):
        query = " ".join(args)
        try:
            voice_channel = ctx.message.author.voice.channel
            song = self.search_yt(query)
            if type(song) == type(True):
                await ctx.send("Could not download the song. Incorrect format try another keyword. This could be due to playlist or a livestream format.")
            else:
                await ctx.send("Song added to the queue")
                self.music_queue.append([song, voice_channel])
        except:
            await message.channel.send("Connect to a voice channel!")

Upvotes: 2

Hunter Boyd
Hunter Boyd

Reputation: 127

If the User is not in a voice channel, Voice will be None, and thus will have no attribute "voice".

Try:

voice_channel = ctx.message.author.voice.channel if ctx.message.author.voice else None

https://discordpy.readthedocs.io/en/stable/api.html#discord.VoiceState

Upvotes: 4

Related Questions