我正在写我的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
因此,这意味着协程不属于关键部分。可能是协同程序无声崩溃,或者因为无法获取锁而超时(如果它实际上是这样工作的话)
尽管如此,我们还是非常感谢帮助解决这个问题
您应该使用^{} statement 而不是
with await
。您还应该在全局名称空间中创建锁,并使用asyncio.sleep
而不是time.sleep
相关问题 更多 >
编程相关推荐