How to define 'client' correctly in a Cog Discord.Py rewrite

Viewed 2611

Trying to get a join / leave command working inside of a Cog. Getting the error "NameError: name 'client' is not defined" when using the command Join. I have tried to use 'self.client' instead but I just get an error that 'self' is not defined. Any help would be super appreciated. Thanks :)

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

class music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    #Events

    #Commands
    #Join Voice Chat
    @commands.command(pass_context=True, aliases=['Join', 'JOIN'])
    async def join(self, ctx):
        channel = ctx.message.author.voice.channel
        voice = get(self.client.voice_clients, guild=ctx.guild)

        if voice and voice.is_connected():
            await voice.move_to(channel)
        else:
            voice = await channel.connect()

        await voice.disconnect()

        if voice and voice.is_connected():
            await voice.move_to(channel)
        else:
                voice = await channel.connect()
                print(f"Bot has connected to {channel}\n")

                await ctx.send(f"Connected to {channel}")
1 Answers

You should create a folder named cogs where every cog will be contained.
When you have cogs, you have to replace every client.commands() by 'commands.command()' and every client occurences by self.client

In your main program file, for instance, bot.py :

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!')
initial_extensions = ['cogs.my_cog'] #cog.(filename)

if __name__ == '__main__':
    for extension in initial_extensions:
        bot.load_extension(extension)

@client.event
async def on_ready():
    print('Bot is ready')

bot.run('Your token')

In your cog program file, for instance, my_cog.py :

import discord
from discord.ext import commands

class My_cog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(pass_context=True, aliases=['Join', 'JOIN'])
    async def join(self, ctx):
        channel = ctx.message.author.voice.channel
        voice = get(self.bot.voice_clients, guild=ctx.guild)

        if voice and voice.is_connected():
            await voice.move_to(channel)
        else:
            voice = await channel.connect()

def setup(bot):
    bot.add_cog(My_cog(bot))
Related