如何仅在满足特定条件的情况下运行后台任务?

时间:2019-01-25 05:24:42

标签: python python-3.x discord discord.py

后台任务不在以下代码中运行。

global bt2
bt2='False'

bot = commands.Bot(command_prefix=!)

@bot.command(pass_context=True)
async def autopurge(ctx,time):
        global bt2, bt2_time, bt2_chid
        bt2='True'
        if int(time)==0:
            bt2='False'
        bt2_time=int(time)
        bt2_chid=ctx.message.channel.id

async def background_task_2():
    global bt2, bt2_time, bt2_chid
    print(bt2, bt2_time, bt2_chid)
    async for msg in bot.logs_from(bt2_chid):
        await bot.delete_message(msg)
    await asyncio.sleep(bt2_time)


while bt2=='True':
    bot.loop.create_task(background_task_2())

它不会删除任何内容。我希望它每隔几秒钟删除一个频道中的消息。

1 个答案:

答案 0 :(得分:2)

当python编译您的代码时,它将执行整个脚本一次,因此您的

while bt2=='True':
    bot.loop.create_task(background_task_2())  

开始运行,并且自bt2='False'开始以来,它不会运行while循环。

如果发生这种情况,您想做什么

global bt2
bt2='False'
purging_task = None

bot = commands.Bot(command_prefix=!)

@bot.command(pass_context=True)
async def autopurge(ctx,time):
  global bt2, bt2_time, bt2_chid,purging_task
  bt2='True'
  if int(time)==0:
    purging_task.cancel()
  elif not(purging_task):
    bt2_time=int(time)
    bt2_chid=ctx.message.channel.id
    purging_task = bot.loop.create_task(background_task_2())

async def background_task_2():
    global bt2, bt2_time, bt2_chid
    while True:
      print(bt2, bt2_time, bt2_chid)
      async for msg in bot.logs_from(bot.get_channel(bt2_chid),limit=5):
        await bot.delete_message(msg)
    await asyncio.sleep(bt2_time)

当您想运行该任务并在该任务中有一个while循环时,可以在哪里运行该任务,而当您要关闭它时,只需运行Task.cancel()

async for msg in bot.logs_from(bt2_chid):
    await bot.delete_message(msg)

不起作用,因为bot.logs_from将频道作为参数而不是其ID