如何在 discord python 中使用 asyncio 打破 while 循环?
How to break a while loop using asyncio in discord python?
client = commands.Bot(command_prefix = '!')
stop_var = False
@client.event
async def on_ready():
print('Bot is ready.')
@client.command()
async def hello(ctx):
while (stop_var==False):
await asyncio.sleep(1)
await ctx.send('Hello!')
if stop_var:
break
@client.command()
async def stop(ctx):
await ctx.send('Stopped!')
stop_var = True
我正在努力做到这一点,当我键入 !stop 时,!hello 命令循环结束,但我的代码不起作用。
这似乎有效:
@client.command()
async def hello(ctx):
stop_var = False
while (not stop_var):
await asyncio.sleep(1)
await ctx.send('Hello!')
def check(msg: discord.Message):
return not msg.author.bot and msg.content.lower() == "!stop"
try:
if await client.wait_for("message", check=check, timeout=1.5):
await ctx.send("Stopped")
stop_var = True
except asyncio.TimeoutError:
print("no stop")
此外,如果您覆盖了 on_command_error
事件,您可以使用它来避免触发它:
@client.command()
async def hello(ctx):
stop_var = False
while (not stop_var):
await asyncio.sleep(1)
await ctx.send('Hello!')
def check(ctx):
return not ctx.author.bot and ctx.command.name == "stop"
try:
if await client.wait_for("command", check=check, timeout=1.5):
stop_var = True
except asyncio.TimeoutError:
print("no stop")
@client.command()
async def stop(ctx):
await ctx.send("Stopped")
client = commands.Bot(command_prefix = '!')
stop_var = False
@client.event
async def on_ready():
print('Bot is ready.')
@client.command()
async def hello(ctx):
while (stop_var==False):
await asyncio.sleep(1)
await ctx.send('Hello!')
if stop_var:
break
@client.command()
async def stop(ctx):
await ctx.send('Stopped!')
stop_var = True
我正在努力做到这一点,当我键入 !stop 时,!hello 命令循环结束,但我的代码不起作用。
这似乎有效:
@client.command()
async def hello(ctx):
stop_var = False
while (not stop_var):
await asyncio.sleep(1)
await ctx.send('Hello!')
def check(msg: discord.Message):
return not msg.author.bot and msg.content.lower() == "!stop"
try:
if await client.wait_for("message", check=check, timeout=1.5):
await ctx.send("Stopped")
stop_var = True
except asyncio.TimeoutError:
print("no stop")
此外,如果您覆盖了 on_command_error
事件,您可以使用它来避免触发它:
@client.command()
async def hello(ctx):
stop_var = False
while (not stop_var):
await asyncio.sleep(1)
await ctx.send('Hello!')
def check(ctx):
return not ctx.author.bot and ctx.command.name == "stop"
try:
if await client.wait_for("command", check=check, timeout=1.5):
stop_var = True
except asyncio.TimeoutError:
print("no stop")
@client.command()
async def stop(ctx):
await ctx.send("Stopped")