Discord bot should skip posting when channel has no new activity

I have a Python Discord bot that automatically posts random content every 6 hours. The problem is that it keeps sending messages even when the channel is inactive. I want to modify the behavior so the bot only posts if there have been new messages from users since its last post.

Current code:

import os
import discord
import asyncio
import random
from content import quote_collection
from copy import deepcopy

token = os.environ['DISCORD_TOKEN']

bot = discord.Client()

async def scheduled_posts():
    await bot.wait_until_ready()
    quotes = deepcopy(quote_collection)
    original_quotes = deepcopy(quote_collection)
    while not bot.is_closed:
        target_channel = bot.get_channel("CHANNEL_ID")
        if not quotes:
            quotes = deepcopy(original_quotes)
        selected_quote = quotes.pop(random.randint(0, len(quotes) - 1))
        await bot.send_message(target_channel, selected_quote)
        await asyncio.sleep(21600)

bot.loop.create_task(scheduled_posts())
bot.run(token)

How can I check for user activity before the bot decides to post?

Track when your bot last posted and compare it to the newest user message. I did this by storing the bot’s last post timestamp, then checking message history before each scheduled post. Store your bot’s last post time in a variable. Before posting, use channel.history() with a limit and set the after parameter to your last post time. Filter out your bot’s messages - if user messages remain, post. If not, skip. Watch out for rate limits when fetching message history too often. I switched to listening for message events instead and using a simple flag that turns on when users post, then resets after the bot posts. Way fewer API calls and does the same thing.

Store your bot’s last message timestamp, then check the channel’s latest message before posting. If that message is newer than yours and isn’t from your bot, go ahead and post. Skip it otherwise. Much easier than dealing with flags or constant event listeners.

Set up an activity tracker with Discord’s event handlers. Use on_message to watch your channel and flip a boolean flag when users post. Start with has_user_activity = False, then switch it to True when you catch non-bot messages. Your scheduled posting function checks this flag first - only sends content when it’s True, then resets to False. Way more efficient than constantly checking message history, and you get real-time tracking. Just filter out your bot’s own messages so you don’t get false triggers.