How do I send a message in a channal at a specific time?
Question:
I want my discord python bot to send a specific message in a channel 2 times a day. First at 12 o’clock and then 18 o’clock in Europe/Berlin time (or just from the server time).
How do I make it? I tried many things but I can’t find a way to do it.
Answers:
You can use APScheduler
and Cron
to schedule your messages to be sent at a specific time, like 12:00 AM
Docs: APScheduler
, Cron
Here is an example:
#async scheduler so it does not block other events
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix="!")
async def func():
await bot.wait_until_ready()
c = bot.get_channel(channel_id)
await c.send("Your Message")
@bot.event
async def on_ready():
print("Ready")
#initializing scheduler
scheduler = AsyncIOScheduler()
#sends "Your Message" at 12PM and 18PM (Local Time)
scheduler.add_job(func, CronTrigger(hour="12, 18", minute="0", second="0"))
#starting the scheduler
scheduler.start()
A slightly modified version of @Just for fun
‘s answer. I carried scheduler
under task()
function that is called from discord.loop.create_task()
and (I adjusted the cron entry).
Solution:
#!/usr/bin/env python3
import logging
import os
from pathlib import Path
import discord
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from broker._utils.tools import get_dt_time
from dotenv import load_dotenv
# In case to disable logging
logging.getLogger("apscheduler.executors.default").propagate = False
class Discord_Bot:
def __init__(self):
dotenv_path = Path(".env_secret")
load_dotenv(dotenv_path=dotenv_path)
self.client = discord.Client()
self.TOKEN = os.getenv("TOKEN")
self.channel_id = int(os.getenv("CHANNEL_ALPY"))
try:
self.client.loop.create_task(self.task())
self.client.loop.run_until_complete(self.client.start(self.TOKEN))
except SystemExit:
pass
# handle_exit()
except KeyboardInterrupt:
# handle_exit()
self.client.loop.close()
print("Program ended")
async def task(self):
scheduler = AsyncIOScheduler()
scheduler.add_job(self.send_message, "cron", hour="12")
scheduler.add_job(self.send_message, "cron", hour="18")
# For test purposes
scheduler.add_job(self.send_message, "cron", minute="*")
scheduler.start()
async def send_message(self, msg=""):
await self.client.wait_until_ready()
channel = self.client.get_channel(self.channel_id)
if not msg:
msg = f"Tick! The time is: {get_dt_time().strftime('%Y-%m-%d %H:%M:%S')}"
await channel.send(msg)
_discord = Discord_Bot()
Example output:
[2021-08-01 14:52:40 base.py:445 - add_job()] Adding job tentatively -- it will be properly scheduled when the scheduler starts
[2021-08-01 14:52:40 base.py:445 - add_job()] Adding job tentatively -- it will be properly scheduled when the scheduler starts
[2021-08-01 14:52:40 base.py:445 - add_job()] Adding job tentatively -- it will be properly scheduled when the scheduler starts
[2021-08-01 14:52:40 base.py:886 - _real_add_job()] Added job "Discord_Bot.send_message" to job store "default"
[2021-08-01 14:52:40 base.py:886 - _real_add_job()] Added job "Discord_Bot.send_message" to job store "default"
[2021-08-01 14:52:40 base.py:886 - _real_add_job()] Added job "Discord_Bot.send_message" to job store "default"
[2021-08-01 14:52:40 base.py:171 - start()] Scheduler started
[2021-08-01 14:52:40 client.py:510 - login()] logging in using static token
[2021-08-01 14:52:42 gateway.py:403 - identify()] Shard ID None has sent the IDENTIFY payload.
[2021-08-01 14:52:42 gateway.py:494 - received_message()] Shard ID None has connected to Gateway: ["gateway-prd-main-jqb3",{"micros":37874,"calls":["discord-sessions-green-prd-2-83",{"micros":36893,"calls":["start_session",{"micros":33555,"calls":["api-prd-main-lx4l",{"micros":30479,"calls":["get_user",{"micros":2553},"add_authorized_ip",{"micros":2438},"get_guilds",{"micros":5864},"coros_wait",{"micros":1}]}]},"guilds_connect",{"micros":1,"calls":[]},"presence_connect",{"micros":2743,"calls":[]}]}]}] (Session ID: ff6cc313c16950abadccfab95a02d3a5).
[2021-08-01 14:53:00 base_py3.py:28 - run_coroutine_job()] Running job "Discord_Bot.send_message (trigger: cron[minute='*'], next run at: 2021-08-01 14:54:00 UTC)" (scheduled at 2021-08-01 14:53:00+00:00)
[2021-08-01 14:53:00 base_py3.py:41 - run_coroutine_job()] Job "Discord_Bot.send_message (trigger: cron[minute='*'], next run at: 2021-08-01 14:54:00 UTC)" executed successfully
discord.py supports scheduling tasks at a specific time after 1.1.0 release. I explained the details in the below answer.
discord.py how to send a message everyday at a specific time
I want my discord python bot to send a specific message in a channel 2 times a day. First at 12 o’clock and then 18 o’clock in Europe/Berlin time (or just from the server time).
How do I make it? I tried many things but I can’t find a way to do it.
You can use APScheduler
and Cron
to schedule your messages to be sent at a specific time, like 12:00 AM
Docs: APScheduler
, Cron
Here is an example:
#async scheduler so it does not block other events
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix="!")
async def func():
await bot.wait_until_ready()
c = bot.get_channel(channel_id)
await c.send("Your Message")
@bot.event
async def on_ready():
print("Ready")
#initializing scheduler
scheduler = AsyncIOScheduler()
#sends "Your Message" at 12PM and 18PM (Local Time)
scheduler.add_job(func, CronTrigger(hour="12, 18", minute="0", second="0"))
#starting the scheduler
scheduler.start()
A slightly modified version of @Just for fun
‘s answer. I carried scheduler
under task()
function that is called from discord.loop.create_task()
and (I adjusted the cron entry).
Solution:
#!/usr/bin/env python3
import logging
import os
from pathlib import Path
import discord
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from broker._utils.tools import get_dt_time
from dotenv import load_dotenv
# In case to disable logging
logging.getLogger("apscheduler.executors.default").propagate = False
class Discord_Bot:
def __init__(self):
dotenv_path = Path(".env_secret")
load_dotenv(dotenv_path=dotenv_path)
self.client = discord.Client()
self.TOKEN = os.getenv("TOKEN")
self.channel_id = int(os.getenv("CHANNEL_ALPY"))
try:
self.client.loop.create_task(self.task())
self.client.loop.run_until_complete(self.client.start(self.TOKEN))
except SystemExit:
pass
# handle_exit()
except KeyboardInterrupt:
# handle_exit()
self.client.loop.close()
print("Program ended")
async def task(self):
scheduler = AsyncIOScheduler()
scheduler.add_job(self.send_message, "cron", hour="12")
scheduler.add_job(self.send_message, "cron", hour="18")
# For test purposes
scheduler.add_job(self.send_message, "cron", minute="*")
scheduler.start()
async def send_message(self, msg=""):
await self.client.wait_until_ready()
channel = self.client.get_channel(self.channel_id)
if not msg:
msg = f"Tick! The time is: {get_dt_time().strftime('%Y-%m-%d %H:%M:%S')}"
await channel.send(msg)
_discord = Discord_Bot()
Example output:
[2021-08-01 14:52:40 base.py:445 - add_job()] Adding job tentatively -- it will be properly scheduled when the scheduler starts
[2021-08-01 14:52:40 base.py:445 - add_job()] Adding job tentatively -- it will be properly scheduled when the scheduler starts
[2021-08-01 14:52:40 base.py:445 - add_job()] Adding job tentatively -- it will be properly scheduled when the scheduler starts
[2021-08-01 14:52:40 base.py:886 - _real_add_job()] Added job "Discord_Bot.send_message" to job store "default"
[2021-08-01 14:52:40 base.py:886 - _real_add_job()] Added job "Discord_Bot.send_message" to job store "default"
[2021-08-01 14:52:40 base.py:886 - _real_add_job()] Added job "Discord_Bot.send_message" to job store "default"
[2021-08-01 14:52:40 base.py:171 - start()] Scheduler started
[2021-08-01 14:52:40 client.py:510 - login()] logging in using static token
[2021-08-01 14:52:42 gateway.py:403 - identify()] Shard ID None has sent the IDENTIFY payload.
[2021-08-01 14:52:42 gateway.py:494 - received_message()] Shard ID None has connected to Gateway: ["gateway-prd-main-jqb3",{"micros":37874,"calls":["discord-sessions-green-prd-2-83",{"micros":36893,"calls":["start_session",{"micros":33555,"calls":["api-prd-main-lx4l",{"micros":30479,"calls":["get_user",{"micros":2553},"add_authorized_ip",{"micros":2438},"get_guilds",{"micros":5864},"coros_wait",{"micros":1}]}]},"guilds_connect",{"micros":1,"calls":[]},"presence_connect",{"micros":2743,"calls":[]}]}]}] (Session ID: ff6cc313c16950abadccfab95a02d3a5).
[2021-08-01 14:53:00 base_py3.py:28 - run_coroutine_job()] Running job "Discord_Bot.send_message (trigger: cron[minute='*'], next run at: 2021-08-01 14:54:00 UTC)" (scheduled at 2021-08-01 14:53:00+00:00)
[2021-08-01 14:53:00 base_py3.py:41 - run_coroutine_job()] Job "Discord_Bot.send_message (trigger: cron[minute='*'], next run at: 2021-08-01 14:54:00 UTC)" executed successfully
discord.py supports scheduling tasks at a specific time after 1.1.0 release. I explained the details in the below answer.
discord.py how to send a message everyday at a specific time