不知道为什么 `asyncio.Lock` 不起作用
Don't know why `asyncio.Lock` is not working
所以它的作用是每当有人在聊天室频道中输入命令 !test
时,它就会在聊天室频道中打印出以下适当的字符串。但是,我希望命令一次只能使用一次,所以我想锁定命令直到它完成:
import discord, asyncio, time
client = discord.Client()
@client.event
async def on_message(message):
lock = Lock() # define Lock
if message.content.lower().startswith("!test") and not lock.locked():
lock.acquire() # Lock the !test command so it can't be used now
await client.send_message(message.channel,'test1rgews')
await asyncio.sleep(1)
await client.send_message(message.channel,'test2thewf')
await asyncio.sleep(1)
await client.send_message(message.channel,'test3rhtvw')
await asyncio.sleep(1)
await client.send_message(message.channel,'test4trjyr')
await asyncio.sleep(1)
await client.send_message(message.channel,'test5dmuye')
await asyncio.sleep(10)
lock.release() # Unlock the !test command now
client.run('clienttokenhere')
但是我得到一个错误 NameError: name 'Lock' is not defined
,即使我确实将其定义为 lock = Lock()
。
导入模块以使用其中的名称是不够的。您必须使用 asyncio.Lock
或 from asyncio import Lock
.
所以它的作用是每当有人在聊天室频道中输入命令 !test
时,它就会在聊天室频道中打印出以下适当的字符串。但是,我希望命令一次只能使用一次,所以我想锁定命令直到它完成:
import discord, asyncio, time
client = discord.Client()
@client.event
async def on_message(message):
lock = Lock() # define Lock
if message.content.lower().startswith("!test") and not lock.locked():
lock.acquire() # Lock the !test command so it can't be used now
await client.send_message(message.channel,'test1rgews')
await asyncio.sleep(1)
await client.send_message(message.channel,'test2thewf')
await asyncio.sleep(1)
await client.send_message(message.channel,'test3rhtvw')
await asyncio.sleep(1)
await client.send_message(message.channel,'test4trjyr')
await asyncio.sleep(1)
await client.send_message(message.channel,'test5dmuye')
await asyncio.sleep(10)
lock.release() # Unlock the !test command now
client.run('clienttokenhere')
但是我得到一个错误 NameError: name 'Lock' is not defined
,即使我确实将其定义为 lock = Lock()
。
导入模块以使用其中的名称是不够的。您必须使用 asyncio.Lock
或 from asyncio import Lock
.