Automatically refreshing external API data in Discord bot every few seconds

I’m working on a Discord bot project and I need to figure out how to automatically refresh data from an external API at regular intervals. Specifically, I want to fetch updated information every 15 seconds or so and make sure my bot always has the latest data available. What’s the best approach to implement this kind of automatic data refresh mechanism? I’ve been experimenting with different methods but I’m not sure which one is most efficient for this type of recurring task. Any suggestions on how to set up this automated refresh system would be really helpful.

def fetch_game_stats():
    response = requests.get('https://api.example.com/player-data')
    player_info = response.json()
    return player_info

# Need to run this automatically every 15 seconds
game_data = fetch_game_stats()

Threading’s another solid option depending on your setup. I used threading.Timer in one of my bots before switching to tasks.loop - worked pretty reliably. Main advantage is it’s simpler if you’re not comfortable with async patterns yet. You just schedule the next execution at the end of each function call. Something like threading.Timer(15.0, fetch_and_schedule).start() where fetch_and_schedule calls your API and sets up the next timer. Downside is you need to watch thread safety when updating shared variables that your bot commands might access. Also remember to cancel active timers when shutting down to avoid zombie threads.

I’ve dealt with this exact scenario before. discord.py’s built-in tasks extension works really well here. The @tasks.loop decorator handles timing automatically and includes error handling. Here’s what worked for me:

from discord.ext import tasks

@tasks.loop(seconds=15)
async def update_game_data():
    try:
        response = await aiohttp.get('https://api.example.com/player-data')
        global game_data
        game_data = await response.json()
    except Exception as e:
        print(f"API fetch failed: {e}")

# Start the task after bot is ready
@bot.event
async def on_ready():
    update_game_data.start()

Watch out for API rate limits - learned this the hard way when my bot got temporarily banned for too many requests. Also make sure you’re using async/await properly since discord.py is async-based, otherwise you’ll block the bot’s main thread.

asyncio.create_task() with a while loop works great if you don’t want the tasks extension. Just wrap your API call in a separate coroutine and let it run in the background. I’ve been using this for months - no issues.