pythonwhile-loopdiscordbots

How to make an endless loop in python for a discord bot?


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.


Solution

  • 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!