I'm just trying to implementation stop command with Task but program returns this code[AttributeError: 'NoneType' object has no attribute 'cancel']
that seems global value didn't store, am I missing knowledge about global value?
how should I implementation this command
import discord
import asyncio
task = None
async def start(message):
while True:
await message.channel.send("loop")
await asyncio.sleep(10)
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
async def on_message(self, message):
if message.author == client.user:
return
if message.content.startswith("!p start"):
global task
task = await client.loop.create_task(start(message))
elif message.content.startswith("!p stop"):
task.cancel()
task = None
client = MyClient()
client.run('TOKEN')
if __name__ == "__main__":
pass
Reformat dumb codes
import discord
import asyncio
class TaskStore():
global task
def __init__(self, task):
self.task = task
async def start(message):
while True:
await message.channel.send("loop")
await asyncio.sleep(10)
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
async def on_message(self, message):
if message.author == client.user:
return
if message.content.startswith("!p start"):
TaskStore.task = await client.loop.create_task(start(message))
elif message.content.startswith("!p stop"):
TaskStore.task.cancel()
TaskStore.task = None
else:
print("not working")
client = MyClient()
client.run('TOKEN')
if __name__ == "__main__":
pass
Error
Ignoring exception in on_message Traceback (most recent call last):
File "discord\client.py", line 270, in _run_event await coro(*args, **kwargs) File "main.py", line 30, in on_message TaskStore.task.cancel() AttributeError: type object 'TaskStore' has no attribute 'task'
task = None
and later you may have message with"!p stop"
so it will executeNone.cancel()
. You have to checkif task is not None
before you can usetask.cancel()
– furasself.task
instead ofglobal
. – furasself.task
created insideMyClient
, not in new class. :) But if you useTaskStore
and__init__
then I would expect you will create instance ofTaskStore
liket = TaskStore(some_task)
. – furasTaskStore.task.cancel()
can be executed beforeTaskStore.task = await client.loop.create_task(start(message))
so you may getNone.cancel()
. You have to checkif TaskStore.task is not None: TaskStore.cancel()
– furas