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

svgewumm  于 2021-09-08  发布在  Java
关注(0)|答案(2)|浏览(320)

我正在制作一个在discord中的小游戏,机器人允许我们在掷骰子上下注,我需要这样做,直到另一个人接受了赌注,它才会运行,所以我试着做了一个while循环来打印“不接受”,直到另一个人键入!接受,但它不起作用,而且由于某些原因,当一个人获胜时,它不会更新字典,因此即使在死亡决斗之后,一个人的分数仍然保持在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
jutyujz0

jutyujz01#

首先,您不想暂停命令。你可以这样做,但它会停止机器人,它不会做任何其他任务,就像你的情况一样。由于使用了repeating sleep()函数,机器人无法检测到!接受命令。您可以做的是,您可以设置一个环境,在那里您可以保存有关赌注的数据(可以是数据库、txt文件或任何文件),并且您可以为该赌注创建一个侦听器!accept命令,其中程序检查之前保存的数据。

siv3szwd

siv3szwd2#

你需要使用 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 是在函数外部定义的字典,这就是为什么不能在函数内部更新它。有两种方法可以解决此问题:
添加 global keys 在函数中,全局变量不是最好的
制作 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`

相关问题