I want to build a Discord bot that automatically posts weather updates every day at 8 AM based on the user’s timezone. The bot should send temperature and weather info without anyone typing a command.
Right now I’m stuck on how to make the bot check if it’s 8 AM locally. I have some helper functions that get the current time in “HH:MM:SS” format but I can’t figure out how to trigger the message automatically.
import discord
from discord.ext import commands
from timeHelper import getLocalTime
# Bot setup
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="?", intents=intents)
api_token = "--------------------------"
@bot.event
async def on_ready():
print("Bot is online!")
@bot.command()
async def about(ctx):
await ctx.send("Hi! I'm your weather bot.")
await ctx.send("I post daily weather updates at 8 AM your local time.")
# This doesn't work - trying to check time
if (getLocalTime() == '08:00:00'):
async def daily_forecast(ctx):
await ctx.send("Weather data will go here")
await ctx.send("This message never shows up")
bot.run(api_token)
I tried putting the if statement inside the function too but that didn’t work either. Is there a way to make the bot run code automatically without someone using a command? I couldn’t find anything in the docs about this.
Your if statement only runs once when the bot starts - that’s the problem. You need a background task that checks the time repeatedly. Use discord.ext.tasks with something like @tasks.loop(minutes=1), then check if it’s 08:00:00 inside that loop. This way your bot actually monitors the time instead of checking once and forgetting about it. Don’t forget timezone handling since Discord users are everywhere. Skip the basic if statements - tasks is what you want here.
you can use discord.ext.tasks for that! just add @tasks.loop(hours=24) above your function and compare local time in it. don’t forget to start it in on_ready or it won’t trigger. kinda tricky but works great!
Your if statement only runs once when the bot starts up, not continuously. I ran into this exact issue building a reminder bot last year. You need a scheduled task with asyncio.create_task() and asyncio.sleep(). Make an async function with an infinite loop that checks the time every minute - when it hits 08:00:00, send your weather message to the channel. Start this background task in your on_ready event with asyncio.create_task(your_function()). This gives you way more control than the tasks extension, especially for timezone stuff and making sure messages only send once per day.