【问题标题】:How to make a background task run only if a certain condition is true?仅当某个条件为真时,如何使后台任务运行?
【发布时间】:2019-06-18 22:34:47
【问题描述】:

后台任务在下面这段代码中没有运行。

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())

它不会删除任何东西。我希望它每隔几秒钟删除一次频道中的消息。

【问题讨论】:

  • 您能解释一下您预计会发生什么以及目前正在发生什么吗?需要满足什么条件?

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


【解决方案1】:

当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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多