python - 如何从另一个命令终止 discord.py 中的异步函数
问题描述
我discord.ext.commands
用来制作一个不和谐的机器人。我做了一个命令,即使有人被禁止,也会不断地取消禁止人。这是代码:
@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)
但这是一个while循环,所以我想通过另一个命令(比如stop_unban)终止这个函数。所以我想知道如何unban
通过另一个函数(与 stop_unban 命令相关联)来终止该函数。
解决方案
一种简单的方法是使用两个函数都可以访问的全局 bool 变量来控制禁止状态。
例如:
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')
但是,如果您希望 unban 模式持续很长时间并且不使用全局变量,另一个可能更好的解决方案可能是使用 abackground task
而不是while True
. 例如:
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()
这是有关后台任务的更多信息:)
推荐阅读
- javascript - 如何交叉过滤 2 dc.js SeriesChart?
- scala - Akka Stream - 带分区的并行处理
- hapi-fhir - StructureDefinition 发布请求返回 404 错误
- shell - shell 中的 sed 函数应用于目录中的所有 .gff 文件
- bigcommerce - 在 Bigcommerce 的任何页面上提取博客数据
- java - Java 重新调整了嵌套列表的元素类型
- mysql - 从 2 个表中选择加入,其中一个表具有来自另一个表的键的数组值
- python - 将数据直接从 BigQuery 加载到 Orange
- matlab - 使用 SVD 确定矩阵列空间的正交基
- python - 我无法从用户那里获取数据来计算