How to schedule a specific function for a Discord bot at designated times

I’m looking to develop a Discord bot that can trigger a certain function at a specific time, for example, 22:30. Additionally, I want the bot to continue its regular operations like handling messages and responding to users outside of that scheduled time.

Here’s the code I’ve tried, but it’s not functioning as expected:

import time
import discord
import myFile
from discord.ext import commands

def launch_discord_bot():
    TOKEN = 'your_token_here'
    intents = discord.Intents.default()
    client = discord.Client(intents=intents)
    target_time = '22:30'

    while True:
        current_time = time.strftime('%H:%M')
        if current_time == target_time:
            myFile.runScheduledFunction()  # this should execute at the designated time
        else:
            @client.event
            async def on_ready():
                print(f'{client.user} is active!')
            
            @client.event
            async def on_message(message):
                if message.author == client.user:
                    return
                username = str(message.author)
                user_message = str(message.content)
                channel = str(message.channel)
                print(f'{username} said: {user_message} ({channel})')
                await sendReply(message)
    client.run(TOKEN)

Any suggestions on how to get this working? I haven’t found useful information online.

Your main problem is calling client.run() inside the while loop - it’ll never get reached. client.run() is blocking and should only be called once to start the bot. You’re also trying to redefine event handlers over and over, which won’t work.

I hit the same issue with my first scheduled bot. Move your scheduling logic inside the bot’s event system using a background task that starts when the bot’s ready:

import discord
import asyncio
import myFile
from datetime import datetime

TOKEN = 'your_token_here'
intents = discord.Intents.default()
client = discord.Client(intents=intents)

async def scheduled_task():
    while True:
        current_time = datetime.now().strftime('%H:%M')
        if current_time == '22:30':
            myFile.runScheduledFunction()
            await asyncio.sleep(60)  # Wait 1 minute to avoid multiple triggers
        await asyncio.sleep(30)  # Check every 30 seconds

@client.event
async def on_ready():
    print(f'{client.user} is active!')
    client.loop.create_task(scheduled_task())

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    username = str(message.author)
    user_message = str(message.content)
    channel = str(message.channel)
    print(f'{username} said: {user_message} ({channel})')
    await sendReply(message)

client.run(TOKEN)

This runs the scheduling check as a background task while keeping the bot responsive to messages and other events.

Your approach has a major flaw - you’re running the bot inside a while loop and redefining event handlers over and over. client.run() should only happen once, and the bot needs to stay connected continuously. I ran into the same issue when I first started with scheduled tasks in Discord bots. Use discord.ext.tasks for scheduling instead of blocking loops. Here’s how to fix it:

import discord
import myFile
from discord.ext import commands, tasks
from datetime import datetime, time

TOKEN = 'your_token_here'
intents = discord.Intents.default()
client = discord.Client(intents=intents)

@tasks.loop(minutes=1)
async def check_scheduled_time():
    current_time = datetime.now().strftime('%H:%M')
    if current_time == '22:30':
        myFile.runScheduledFunction()

@client.event
async def on_ready():
    print(f'{client.user} is active!')
    check_scheduled_time.start()

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    # your message handling logic here
    await sendReply(message)

client.run(TOKEN)

This keeps the bot connected and handles both scheduled tasks and regular events properly.

the issue is running client.run in a loop; it blocks your bot. use asyncio.create_task for scheduling. I’ve made bots like that before, and a bg coroutine checking the time works best with your bot events. discord.py takes care of async well, so keep it simple.