Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send message without command or event discord.py

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!

like image 917
Remi_Zacharias Avatar asked Oct 28 '25 15:10

Remi_Zacharias


1 Answers

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')
like image 187
Benjin Avatar answered Oct 31 '25 06:10

Benjin