Skip to content
Advertisement

In Discord.py, is it possible to wait for a variable to change from a different part of the code than the variable changes?

I tried using time.sleep(), but instead of waiting for the variable it paused the whole code, not allowing the variable to change. This is my code:

@tasks.loop(seconds=5.0) #This is the code that changes the variable (Before this block of code, the variable fedex is defined)
  global check, fedex
  fedex = int(fedex) + r.randint(-500,500)
  if(check=="0"):
    check = "1"
  else:
    check = "0"

@client.command() #This is the code in which, after the variable changes, the bot should type if the variable fedex went up or down.
async def bet(ctx, arg1):
  def new():
    global current
    if(arg1=="fedex"):
      global fedex
      current = fedex
    else:
      return
  new()
  stok = current
  if(check=="0"):
    while(check != "1"):
      time.sleep(1.0)
  elif(check=="1"):
    while(check != "0"):
      time.sleep(1.0)
  new()
  stok2 = current
  if(stok2>stok):
    await ctx.send("It went up!")
  else:
    await ctx.send("It went down.")

I can’t figure out what to replace time.sleep(1.0) with.

Advertisement

Answer

You can use await asyncio.sleep(1) instead. Asyncio.sleep works like time.sleep, but it doesn’t block the entire code execution. It stops only one event. Meanwhile, other tasks in your event loop will continue running. While using time.sleep your entire code doesn’t do anything else. However, asyncio.sleep asks the event loop to do other tasks while part of your code is “sleeping”.

Great explanation with examples

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement