尝试同步 discord.py 命令时无法获取锁

Can't acquire lock when trying to synchronize discord.py commands

我正在编写我的 discord 机器人,它有一些命令。但是,最近出现了每个命令在执行前都需要检查列表的情况。所以,正确的做法自然是同步命令,像这样:

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

所以,这意味着协程没有落入临界区。可能是协程无声地崩溃或因​​无法获取锁而超时(如果它实际上是这样工作的)。

不过,非常感谢您帮助解决这个问题。

您应该使用 async with statement 而不是 with await。您还应该在全局命名空间中创建锁,并使用 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')