Skip to content Skip to sidebar Skip to footer

Discord.py How To Send A Message Everyday At A Specific Time

I want to create a discord bot that sends 2 messages every day each at a specific time. The following code will make the messages enter a loop and will send a message every 5 secon

Solution 1:

Here's a simple implementation - Every day, it sleeps until the target time and then sends your message

from discord.ext import commands
from datetime import datetime, time, timedelta
import asyncio

bot = commands.Bot(command_prefix="$")
WHEN = time(18, 0, 0)  # 6:00 PM
channel_id = 1# Put your channel id hereasyncdefcalled_once_a_day():  # Fired every dayawait bot.wait_until_ready()  # Make sure your guild cache is ready so the channel can be found via get_channel
    channel = bot.get_channel(channel_id) # Note: It's more efficient to do bot.get_guild(guild_id).get_channel(channel_id) as there's less looping involved, but just get_channel still works fineawait channel.send("your message here")

asyncdefbackground_task():
    now = datetime.utcnow()
    if now.time() > WHEN:  # Make sure loop doesn't start after {WHEN} as then it will send immediately the first time as negative seconds will make the sleep yield instantly
        tomorrow = datetime.combine(now.date() + timedelta(days=1), time(0))
        seconds = (tomorrow - now).total_seconds()  # Seconds until tomorrow (midnight)await asyncio.sleep(seconds)   # Sleep until tomorrow and then the loop will start whileTrue:
        now = datetime.utcnow() # You can do now() or a specific timezone if that matters, but I'll leave it with utcnow
        target_time = datetime.combine(now.date(), WHEN)  # 6:00 PM today (In UTC)
        seconds_until_target = (target_time - now).total_seconds()
        await asyncio.sleep(seconds_until_target)  # Sleep until we hit the target timeawait called_once_a_day()  # Call the helper function that sends the message
        tomorrow = datetime.combine(now.date() + timedelta(days=1), time(0))
        seconds = (tomorrow - now).total_seconds()  # Seconds until tomorrow (midnight)await asyncio.sleep(seconds)   # Sleep until tomorrow and then the loop will start a new iterationif __name__ == "__main__":
    bot.loop.create_task(background_task())
    bot.run('token')

Solution 2:

I created a [Discord-bot] That sends a message at a particular time and until that time comes it will be in a sleep. the code i created is small and easy to understand Code:

import discord
from datetime import datetime

client = discord.Client()
token = ""#enter your bot's token and it should be a string
channel_id = #enter your channel id and it should be a integer   deftime_module():
    print("time module in use")
    whileTrue:created
        current_time = datetime.now().strftime("%H:%M")#hour %H min %M sec %S am:pm %p if current_time == "00:00": # enter the time you wish print("time module ended")
            break

time_module()

@client.eventasyncdefon_ready():

    print("bot:user ready == {0.user}".format(client))
    channel = client.get_channel(channel_id)
    await channel.send("message")
    

client.run(token)

Solution 3:

You will need to figure the time of now, and the time that you schedule, then every like 10 or fewer minutes you check if the scheduled time meets the now.

check this link to see the DateTime library for python https://docs.python.org/3/library/datetime.html#datetime.datetime.now

and check this link to see an example of how to use @tasks.loop (background task) https://github.com/Rapptz/discord.py/blob/master/examples/background_task.py

to get the time of now using the dateTime library

now=datetime.datetime.now() #will store the time of when it is called#if you want to put specific time:
remindMeAT =datetime.datetime(2021,5,4,17,24)  #year,month,day,hour,min,sec

Solution 4:

You have to make a before_loop so that the first time it runs it will be on time after that just make the loop every 24 hours. Here is an example.

import asyncio
import datetime as dt


@bot.eventasyncdefon_ready():
    print("Logged in as")
    print(bot.user.name)
    print("------")
    msg1.start()


# Message 1@tasks.loop(hours=24)asyncdefmsg1():
    message_channel = bot.get_channel(705524214270132367)
    await message_channel.send("test 1")


@msg1.before_loopasyncdefbefore_msg1():
    for _ inrange(60*60*24):  # loop the whole dayif dt.datetime.now().hour == 10+12:  # 24 hour formatprint('It is time')
            returnawait asyncio.sleep(1)# wait a second before looping again. You can make it more 

Post a Comment for "Discord.py How To Send A Message Everyday At A Specific Time"