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

2024-04-25 13:11:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写我的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

因此,这意味着协程不属于关键部分。可能是协同程序无声崩溃,或者因为无法获取锁而超时(如果它实际上是这样工作的话)

尽管如此,我们还是非常感谢帮助解决这个问题


Tags: infromimport命令clientsendlocklogging
1条回答
网友
1楼 · 发布于 2024-04-25 13:11:19

您应该使用^{} 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')

相关问题 更多 >