Weird timing issues with my Discord bot's scheduled messages

Hey everyone! I’m having a strange problem with my Discord bot. I want it to send a message every 30 minutes, but it’s acting really funky. Sometimes it sends messages at odd times, and other times it spams multiple messages at once. It’s driving me crazy!

Here’s what my code looks like:

@bot.event
async def on_start():
    await message_loop()

async def message_loop():
    print('Starting message loop')
    chat = bot.get_channel(SOME_CHANNEL_ID)
    await chat.send(f'Check out this cool {random_thing}!')
    print(random_thing)
    await asyncio.sleep(1800)
    await message_loop()

I tried using time.sleep instead of asyncio.sleep, but that made the bot time out. It also caused the message_loop() function to run twice, once from on_start and once from itself. Now the bot sends two messages, but at least it’s consistent.

My friends and I have been scratching our heads over this for hours. Any ideas on how to fix this timing issue? I just want my bot to behave and send messages every half hour like a good bot should!

I encountered a similar issue when developing my own Discord bot. The problem likely stems from the recursive nature of your message_loop function. Instead, consider implementing a background task using Discord.py’s built-in features. Here’s a snippet that might help:

@tasks.loop(minutes=30)
async def scheduled_message():
    channel = bot.get_channel(SOME_CHANNEL_ID)
    await channel.send(f'Check out this cool {random_thing}!')

@bot.event
async def on_ready():
    scheduled_message.start()

This approach ensures the message is sent every 30 minutes without recursion issues. It’s more efficient and less prone to timing discrepancies. Remember to import the necessary modules and adjust the code to fit your specific bot structure.

hav u tried using a scheduler library like apscheduler? it can handle recurring tasks better than manual loops. also, ur current setup might cause issues with multiple instances running. make sure ur only calling message_loop() once and not recursively. good luck fixing it!

I’ve been through this exact headache with my own Discord bot. The issue is likely stemming from the recursive nature of your message_loop function. It can cause weird timing issues and even stack up multiple instances of the function running simultaneously.

Here’s what worked for me:

I switched to using Discord.py’s built-in task scheduler. It’s much more reliable for handling timed events. Your code could look something like this:

from discord.ext import tasks

@tasks.loop(minutes=30)
async def scheduled_message():
    channel = bot.get_channel(SOME_CHANNEL_ID)
    await channel.send(f'Check out this cool {random_thing}!')

@bot.event
async def on_ready():
    scheduled_message.start()

This approach eliminated all the timing weirdness I was experiencing. Plus, it’s way cleaner and easier to manage. Give it a shot and see if it solves your problem too!