如何在等待另一个命令时暂停 discord.py 中的命令

时间:2021-07-09 06:08:18

标签: python discord.py

我正在制作一个不和谐的迷你游戏,机器人允许我们在掷骰子上下注,我需要让它在另一个人接受下注之前不会运行,所以我尝试制作一个 while 循环来打印不接受,直到其他人输入 !accept 但它不起作用,并且由于某种原因,当一个人获胜时它不会更新字典,因此即使在死亡投票后,一个人的积分仍然保持 1000,无论输赢

代码:

@client.command()
async def deathroll(ctx,user:discord.User,bet=100):
    roller1 = ctx.author.id
    roller2 = user.id
    accepted=False
    if roller1 not in keys:
        await ctx.send("make an account first")
    if roller2 not in keys:
        await ctx.send("please give a user for roller2")
    while accepted!=True:
        print("not accepted")
        time.sleep(10)
    if roller2 in keys:
        roll=100
        while roll!=1:
            roll=random.randint(1,roll)
            await ctx.send("roller1,rolled:"+str(roll))
            if roll==1:
                await ctx.send("the winner is roller1")
                keys[roller1]=keys[roller1]-bet
                keys[roller2]=keys[roller2]+bet
                break
            roll=random.randint(1,roll)
            await ctx.send("roller2,rolled:"+str(roll))
            if roll == 1:
                await ctx.send("the winner is roller1")
                keys[roller2]=keys[roller2]-bet
                keys[roller1]=keys[roller1]+bet
                break

@client.command()
async def accept(ctx):
    accepted=True

2 个答案:

答案 0 :(得分:0)

首先,您不想暂停命令。您可以这样做,但它会停止机器人,并且它也不会执行任何其他任务,就像您的情况一样。由于重复的 sleep() 函数,机器人无法检测到 !accept 命令。您可以做的是设置一个环境,您可以在其中保存有关赌注的数据(可以是数据库、txt 文件等),并监听 !accept 命令,程序会在其中检查保存的数据之前。

答案 1 :(得分:0)

您需要使用 wait_for,它等待给定的事件并且也是异步的

@client.command()
async def deathroll(ctx,user:discord.User,bet=100):
    roller1 = ctx.author.id
    roller2 = user.id
    if roller1 not in keys:
        await ctx.send("make an account first")
    if roller2 not in keys:
        await ctx.send("please give a user for roller2")
    msg = await client.wait_for("message", check=lambda m: m.author.id == user.id) # make sure that it only goes ahead when the mentioned user sends !accept
    while msg.content != "!accept":
        msg = await bot.wait_for("message", check=lambda m: m.author.id == user.id)

我假设 keys 是在函数外部定义的字典,这就是为什么你不能在函数内部更新它 有两种方法可以解决这个问题:

  1. 在函数中添加global keys,全局变量不是最好的
  2. 使 keys 成为机器人变量

第一种方式:

@client.command()
async def deathroll(ctx,user:discord.User,bet=100):
    global keys
    ...

第二种方式:

# wherever u define keys = {} do this instead
client.keys = {}
# then use client.keys[roller1] = client.keys[roller1]-bet
# basically replace `keys` with `client.keys`