创建一个单独的停止命令,该命令可用于中断discord.py中的循环



我目前正在尝试不协调地编写一个问答机器人程序,而现在我在创建一个可用于停止会话的命令时遇到了问题。这就是我到目前为止所想到的:

@client.command()
async def ask(ctx):
quiz_data = {
'question_1': (["1", "one"], "one"),
'question_2': (["2", "two"], "two"),
}
question = random.choice(list(quiz_data.keys()))
answers, hint = quiz_data[question]
await ctx.send("What is the answer to this question?")
await asyncio.sleep(1)
await ctx.send(question)
def check_sender(msg): 
return msg.author == ctx.author and msg.channel == ctx.channel
def check_answer(msg):
return any(answer in msg.content.lower() for answer in answers)
try:
async with timeout(10):
while True:
def running(self):
return True
msg = await client.wait_for('message', check=check_sender)
if check_answer(msg):
await ctx.send("good")
break
else:
print('someone got it wrong lol')
except asyncio.TimeoutError:
await ctx.send(f"What is the answer to this question? hint: {hint}")
await ctx.send(question)
msg = await client.wait_for('message', check=check_sender)
if check_answer(msg):
await ctx.send("good")
else:
await ctx.send("wrong.")

@client.command()
async def stopg(ctx):
if running() == True:
await ctx.send("Round is stopping...")
else: 
await ctx.send("No round active")

命令stopg目前不起作用,因为running仅在前一个命令中定义。这是我决定使用的尝试,因为我认为这可以解释我想最容易完成的事情;创建一个指示器,用于判断循环或命令是否正在运行,该指示器将作为if语句应用于stop命令中。老实说,自从几天前我突然想到这件事以来,我还没有对此做过那么多研究。

很抱歉,如果这没有多大意义,我愿意回答任何问题。或者任何其他方式,如果我提到的是过于复杂的事情。非常感谢~。

您可以执行类似while someVariable的操作,而不是执行while True,然后编程stop函数来更改变量someVariable的值。然后,您还可以通过检查变量someVariable本身来检查循环是否正在运行。

干杯,

最新更新