Rohit Manjunath
Rohit Manjunath

Reputation: 113

How to make a background task run only if a certain condition is true?

The background task does not run in the following piece of code.

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

It does not delete anything. I want it to delete messages in a channel every couple of seconds.

Upvotes: 2

Views: 384

Answers (1)

Tristo
Tristo

Reputation: 2408

When python compiles your code it executes the whole script once, so your

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

gets run and since bt2='False' at the start, it won't run the while loop.

What you want to do instead if something like this

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)

Where you would run the task when you want to run and have a while loop within that task, and when you want to close it simply run Task.cancel()

Also

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

doesn't work since bot.logs_from takes a channel as an argument, not its id

Upvotes: 2

Related Questions