我只是试图用Task实现stop命令,但是程序返回了此代码
[AttributeError: 'NoneType' object has no attribute 'cancel']
,似乎没有存储全局值,我是否缺少有关全局值的知识? br />我应该如何执行该命令
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
重新格式化哑代码
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
错误
忽略on_message追溯中的异常(最近一次调用为最新):
_run_event中的文件“ discord \ client.py”,第270行 等待coro(* args,** kwargs)文件“ main.py”,第30行,在on_message中 TaskStore.task.cancel()AttributeError:类型对象'TaskStore'没有属性'task'
答案 0 :(得分:0)
我完全感到困惑,有一些我正在尝试实现的代码
我感谢furas,谢谢您的帮助!
已解决
import discord
import asyncio
class TaskStore():
task = None
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"):
if TaskStore.task != True:
global task
task = client.loop.create_task(start(message))
TaskStore.task = True
else:
await message.channel.send("bot is currently working on it")
elif message.content.startswith("!p stop"):
if TaskStore.task is not None and not False:
task.cancel()
TaskStore.task = False
await message.channel.send("bot will be off")
else:
await message.channel.send("bot is currently not working")
client = MyClient()
client.run('TOKEN')
if __name__ == "__main__":
pass