I am using the datetime file, to print: It's 7 am, every morning at 7. Now because this is outside a command or event reference, I don't know how I would send a message in discord saying It's 7 am. Just for clarification though, this isn't an alarm, it's actually for my school server and It sends out a checklist for everything we need at 7 am.
import datetime
from time import sleep
import discord
time = datetime.datetime.now
while True:
print(time())
if time().hour == 7 and time().minute == 0:
print("Its 7 am")
sleep(1)
This is what triggers the alarm at 7 am I just want to know how to send a message in discord when this is triggered.
If you need any clarification just ask. Thanks!
You can create a background task that does this and posts a message to the required channel.
You also need to use asyncio.sleep() instead of time.sleep() as the latter is blocking and may freeze and crash your bot.
I've also included a check so that the channel isn't spammed every second that it is 7 am.
discord.py v2.0
from discord.ext import commands, tasks
import discord
import datetime
time = datetime.datetime.now
class MyClient(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.msg_sent = False
async def on_ready(self):
channel = bot.get_channel(123456789) # replace with channel ID that you want to send to
await self.timer.start(channel)
@tasks.loop(seconds=1)
async def timer(self, channel):
if time().hour == 7 and time().minute == 0:
if not self.msg_sent:
await channel.send('Its 7 am')
self.msg_sent = True
else:
self.msg_sent = False
bot = MyClient(command_prefix='!', intents=discord.Intents().all())
bot.run('token')
discord.py v1.0
from discord.ext import commands
import datetime
import asyncio
time = datetime.datetime.now
bot = commands.Bot(command_prefix='!')
async def timer():
await bot.wait_until_ready()
channel = bot.get_channel(123456789) # replace with channel ID that you want to send to
msg_sent = False
while True:
if time().hour == 7 and time().minute == 0:
if not msg_sent:
await channel.send('Its 7 am')
msg_sent = True
else:
msg_sent = False
await asyncio.sleep(1)
bot.loop.create_task(timer())
bot.run('TOKEN')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With