0
votes

I'm new to discord.py and following the tutorials on cogs. I followed everything the tutorial told me, but I got a name error when I run a command.

Here's the code:

./bot.py

import os
import discord
from discord.ext import commands

client = commands.Bot(command_prefix = '/')

@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.online, activity=discord.Game('Under Development'))
    print('Bot Online')

@client.command()
async def load(ctx, extension):
    client.load_extension(f'cogs.{extension}')

@client.command()
async def unload(ctx, extension):
    client.unload_extension(f'cogs.{extension}')

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')

client.run(os.environ['TOKEN'])

./cogs.commands.py

import discord
from discord.ext import commands

class Commands(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def ping(self, ctx):
        await ctx.send(f'Network Delay: **{round(client.latency * 1000)} ms**')

def setup(client):
    client.add_cog(Commands(client))

when I type /ping in discord message box, I got this traceback

Traceback (most recent call last): File "C:\Users\bryan\source\repos\discord_music_bot\env\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke await ctx.command.invoke(ctx) File "C:\Users\bryan\source\repos\discord_music_bot\env\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke await injected(*ctx.args, **ctx.kwargs) File "C:\Users\bryan\source\repos\discord_music_bot\env\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'client' is not defined

1
What do you expect client to be in Commands.ping? Did you mean to write self.client?Brian
well, since i'm new to discord.py, i got no idea what i'm doing and just follow the tutorialTheNoobProgrammer
after seeing the error once more in the terminal, i think i got an idea where the error might be in.TheNoobProgrammer

1 Answers

1
votes

thanks to @Brian, i finally fixed the error. I write client.latency instead of self.client.latency

async def ping(self, ctx):
        await ctx.send(f'Network Delay: **{round(self.client.latency * 1000)} ms**')