简体   繁体   English

如何从另一个命令终止 discord.py 中的异步 function

[英]How to terminate an async function in discord.py from another command

I'm using discord.ext.commands to make a discord bot.我正在使用discord.ext.commands制作一个 discord 机器人。 I made a command that constantly keeps unbanning people even if someone is banned.我做了一个命令,即使有人被禁止,也会不断地取消禁止。 This is the code:这是代码:

@client.command(name="unban")
async def unban(ctx):
  while True:
    bans = await ctx.guild.bans()
    if(len(bans)>0):
      for ban in bans:
        ctx.guild.unban(ban)
    await asyncio.sleep(5)

But this is a while loop so I want to terminate this function through another command (say, stop_unban).但这是一个 while 循环,所以我想通过另一个命令(比如 stop_unban)终止这个 function。 So I want to know how to terminate the unban function through another function (associated with the stop_unban command).所以我想知道如何通过另一个 function(与 stop_unban 命令相关联)终止unban function。

A simple way would be to use a global bool variable that both functions can access to control the banning state.一种简单的方法是使用两个函数都可以访问的全局 bool 变量来控制禁止 state。
For example:例如:

ban_state = False
@client.command(name="unban")
async def unban(ctx):
  global ban_state
  ban_state = True
  while ban_state:
    bans = await ctx.guild.bans()
    if(len(bans)>0):
      for ban in bans:
        await ctx.guild.unban(ban.user)
    await asyncio.sleep(5)
@client.command(name="stop_unban")
async def stop_unban(ctx):
  global ban_state
  ban_state = False
  await ctx.send('Unban Mode stopped')

However, another potentially nicer solution if you want the unban mode to last for long periods as well as not using global variables could be to use a background task instead of the while True .但是,如果您希望 unban 模式持续很长时间并且不使用全局变量,另一个可能更好的解决方案可能是使用background task而不是while True For example:例如:

from discord.ext import tasks
@tasks.loop(seconds=5.0)
async def unbanning(ctx):
    bans = await ctx.guild.bans()
    if(len(bans)>0):
      for ban in bans:
        await ctx.guild.unban(ban.user) #btw you need to await this and you have provide the user attribute of the ban not just the ban itself
    
@client.command(name="unban")
async def unban(ctx):
  unbanning.start(ctx)
@client.command(name="stop_unban")
async def stop_unban(ctx):
  unbanning.cancel()

Here is more info on background tasks:) 是有关后台任务的更多信息:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM