使用命令在 discord.py 中停止 while true 循环

stopping while true loop in discord.py with command

我正在 discord bot 中制作一个简单的 crash gamble 命令,但我不知道,当我使用 !crash money 时,如何使用 !stop 停止它。我有一个 while True 循环,我想用命令 !stop 以某种方式打破 while true 循环,我不知道如何制作命令。

简化代码

@client.command()
async def crash(ctx, amount = None):
 multiplier = 1
 while True:
  multiplier += 0.2
  #here i would like something, when author of the crash command will write !stop, it will break the while true loop 
 win_amount = int(multiplier*amount)

您可以简单地创建一个变量,告诉停止命令何时为 运行,如下所示:

@client.command()
async def stop():
    global stopVar
    stopVar = True

@client.command()
async def crash(ctx, amount = None):
    global stopVar
    stopVar = False
    multiplier = 1
    while True:
    multiplier += 0.2
    if stopVar:
        break
    win_amount = int(multiplier*amount)

显然,如果你想让它成为多人可以同时玩的地方,就必须添加,但要使变量 user-dependant。可能还需要其他功能。

使其成为作者特定的一种简单方法是向 stop 函数添加字典:

#example (not working code)
@client.command()
async def stop(ctx):
    global stopDict
    stopDict[ctx.message.author] = True