How to send message without command or event discord.py

Viewed 9545

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!

3 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.

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')

From the Discord.py docs when you have a client setup, you can directly send a message to a channel using the format:

channel = client.get_channel(12324234183172)
await channel.send('hello')

Once you have your channel (after you have setup your client), you can place that snippet of code edited as needed to select the appropriate channel along with the needed message. Keep in mind "You can only use await inside async def functions and nowhere else." so you need to setup an async function to do so and your simple While True: loop may not work

Related