Python Can';尝试同步discord.py命令时,无法获取锁
我正在写我的discord机器人,它有几个命令。然而,最近出现了对每个命令在执行之前检查列表的需求。因此,正确的做法自然是同步命令,如下所示:Python Can';尝试同步discord.py命令时,无法获取锁,python,python-asyncio,discord.py-rewrite,Python,Python Asyncio,Discord.py Rewrite,我正在写我的discord机器人,它有几个命令。然而,最近出现了对每个命令在执行之前检查列表的需求。因此,正确的做法自然是同步命令,如下所示: import discord from discord.ext import commands from time import sleep import subprocess import logging import asyncio client = commands.Bot(command_prefix='>>', case_inse
import discord
from discord.ext import commands
from time import sleep
import subprocess
import logging
import asyncio
client = commands.Bot(command_prefix='>>', case_insensitive=True)
token = 'lul'
logging.basicConfig(level=logging.INFO)
lock = None
@client.event
async def on_ready():
lock = asyncio.Lock()
print(f'Logged in as {client.user}')
@client.command()
async def test(ctx, members : commands.Greedy[discord.Member]):
await ctx.send(len(members))
await ctx.send('approaching critical section')
with await lock:
await ctx.send('in critical section')
time.sleep(10)
await ctx.send('exited critical section')
因此,如果您使用>test@abs@asda
调用该命令,您将收到以下输出:
2
approaching critical section
in critical section
exited critical section
但我们得到的是:
2
approaching critical section
因此,这意味着协程不属于关键部分。可能是协同程序无声崩溃,或者因为无法获取锁而超时(如果它实际上是这样工作的话)
尽管如此,我们还是非常感谢您对解决此问题的帮助。您应该在wait中使用而不是。您还应该在全局命名空间中创建锁,并使用asyncio.sleep
而不是time.sleep
client = commands.Bot(command_prefix='>>', case_insensitive=True)
lock = asyncio.Lock() # Doesn't require event loop
@client.command()
async def test(ctx, members : commands.Greedy[discord.Member]):
await ctx.send(len(members))
await ctx.send('approaching critical section')
async with lock:
await ctx.send('in critical section')
await asyncio.sleep(10)
await ctx.send('exited critical section')