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:
JavaScript
x
2
1
"NameError: name 'ctx' is not defined"
2
Here is part of my code that uses the ctx command. The aim is to get it to delete the last 3 messages sent.
JavaScript
1
20
20
1
@client.event
2
async def purge(ctx):
3
"""clear 3 messages from current channel"""
4
channel = ctx.message.channel
5
await ctx.message.delete()
6
await channel.purge(limit=3, check=None, before=None)
7
return True
8
9
10
11
@client.event
12
async def on_message(message):
13
if message.content.startswith("purge"):
14
await purge(ctx)
15
16
17
18
client.run(os.environ['TOKEN'])
19
20
Full error:
JavaScript
1
8
1
Ignoring exception in on_message
2
Traceback (most recent call last):
3
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
4
await coro(*args, **kwargs)
5
File "main.py", line 31, in on_message
6
await purge(ctx)
7
NameError: name 'ctx' is not defined
8
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:
JavaScript
1
10
10
1
async def purge(message):
2
await message.delete()
3
channel = message.channel
4
await channel.purge(limit=3)
5
6
@client.event
7
async def on_message(message):
8
if message.content.startswith("purge"):
9
await purge(message)
10
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