How to send message without command or event discord.py

Question:

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!

Asked By: Remi_Zacharias

||

Answers:

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

Answered By: Karan Shishoo

From the documentation of discord.py, you first need to fetch the channel by its id and then you can send a message.

See: https://discordpy.readthedocs.io/en/latest/faq.html#how-do-i-send-a-message-to-a-specific-channel

You must fetch the channel directly and then call the appropriate method. Example:

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

Hope, this helps.

Answered By: dabins

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')
Answered By: Benjin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.