Skip to content
Advertisement

Discord.py ctx commands not recognised

im fairly new to coding in general and recently started trying to code my own bot. Almost all of the tutorials i have seen use the ctx command however, whenever i use it i get this error:

 "NameError: name 'ctx' is not defined"

Here is part of my code that uses the ctx command. The aim is to get it to delete the last 3 messages sent.

    @client.event
async def purge(ctx):
    """clear 3 messages from current channel"""
    channel = ctx.message.channel
    await ctx.message.delete()
    await channel.purge(limit=3, check=None, before=None)
    return True



@client.event
async def on_message(message):
    if message.content.startswith("purge"):
        await purge(ctx)



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

Full error:

Ignoring exception in on_message
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 31, in on_message
    await purge(ctx)
NameError: name 'ctx' is not defined

I’m hosting the server on repl.it if that makes any difference and as i said, im pretty new to coding so it’s possible i have missed something very obvious, any help is appreciated. ^_^

Advertisement

Answer

A fix to that is:

async def purge(message):
    await message.delete()
    channel = message.channel
    await channel.purge(limit=3)

@client.event
async def on_message(message):
    if message.content.startswith("purge"):
        await purge(message)  

The problem is the on_message function uses message and not ctx. Replacing message with ctx wont work because im pretty sure the on_message cant use ctx

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement