-1

I am trying to make a discord bot using python which takes data from an API, compares to it to the previous data I had (also from same API) and checks whether there is any difference in the first 25 items returned, if there is I want to send that as message to a channel on discord. I want to get the data from API every 2 seconds so I have made a while loop for this. But for running the bot we need to use bot.run('token') at the end of code but since my loop is basically infinite it will never reach that line.

Following is the outline of the code

# import whatever necessary

# declare constants/variables

# define functions needed

# define time step
time_step = 2

# while loop starts
while True:
    # take new API data and store it in a file
    # compare the previous data and current data and get what's necessary
    # ***Want to print with the bot here***
    # replace old file data with the new file data
    # close files
    # sleep till time for this iteration of while is not equal to time_step (2 seconds)
    continue # after 2 seconds have been completed in this while iteration

run.bot('token') # but it will never reach this line as the while loop is infinite

From what I have tried the run.bot() needs to be at last or it just doesn't work and I counldn't find any relevant examples either. Any help would be appreciated.

  • your while loop cannot be empty. put a `pass` inside it if you want an infinite loop that does nothing, otherwise the code as you have it now will produce a syntax error. – Sembei Norimaki Apr 20 '23 at 10:32
  • @sembei, the while is not empty, it takes new data from the API and manipulates as I want every time it runs – Gautam Bansal Apr 20 '23 at 10:42
  • The fact is, the code you posted has an empty `while True:` loop, which is a syntax error. Please review the [help] and in particular [How to ask](/help/how-to-ask) as well as the guidance for providing a [mre]. – tripleee Apr 20 '23 at 11:30
  • I see where the confusion is, I have edited the code accordingly. – Gautam Bansal Apr 20 '23 at 11:59

1 Answers1

0

An approach to solving this could be to run your while loop as a task from discord.py. This will allow you to send discord messages inside your loop or do whatever discord-related things you want.

Essentially, you'll put your API accessing code inside a task similar to the following:

from discord.ext import tasks

@bot.event
async def on_ready():
    task_loop.start() # important to start the loop

@tasks.loop(seconds=2)
async def task_loop():
    ... # Put your API accessing here instead of a while loop and call whatever discord related stuff you desire.

For more information read:

Any other questions or if you can't get this to work let me know. Have a great day/night!