1. Implementing reminder mechanisms
Using the modules datetime
and
timedelta
Sometimes, you need to calculate how much time is left before an event to create a reminder. Here's where timedelta
comes in handy:
from datetime import datetime, timedelta
# Calculating reminder time
meeting_time = datetime(2023, 10, 30, 15, 0, 0)
reminder_time = meeting_time - timedelta(minutes=30)
print(f"You need to send a reminder at: {reminder_time}")
Simple notification via console
The first step is simple notifications. Sure, they’re not as "fancy" as push notifications on your smartphone, but it’ll do for starters.
import time
def simple_reminder(message, delay):
print(f"In {delay} seconds, a reminder will follow...")
time.sleep(delay)
print(f"Reminder: {message}")
simple_reminder("It's time for the meeting!", 10)
2. Using schedule
for periodic reminders
When you need reminders to repeat, schedule
becomes your buddy. You can set different intervals, like daily or weekly:
import schedule
import time
def meeting_reminder():
print("Reminder: You have a meeting soon!")
# Reminder every day at 2:30 PM
schedule.every().day.at("14:30").do(meeting_reminder)
while True:
schedule.run_pending()
time.sleep(1)
3. Time-based notifications using the plyer
library
To make notifications more "real", we can use the plyer
library to send system notifications:
from plyer import notification
import time
def plyer_notification(title, message):
notification.notify(
title=title,
message=message,
app_name='Python Reminder',
timeout=10
)
# Example usage
plyer_notification("Reminder!", "It's time for the meeting.")
The function notification.notify()
will display a standard OS notification.
4. Email reminders
To send email notifications in Python, the smtplib
module is used. In the next example, we'll set up email reminders using an SMTP server.
import smtplib
from email.mime.text import MIMEText
import schedule
import time
def send_email_reminder():
sender = "your_email@example.com"
receiver = "receiver_email@example.com"
subject = "Task Reminder"
body = "This is an automatic reminder: Don't forget to complete your task today."
# Creating the message
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = sender
msg["To"] = receiver
# Connecting to the SMTP server and sending the email
with smtplib.SMTP("smtp.example.com", 587) as server:
server.starttls()
server.login(sender, "your_password")
server.sendmail(sender, receiver, msg.as_string())
print("Reminder sent via email.")
# Schedule the reminder to be sent daily at 8:30 AM
schedule.every().day.at("08:30").do(send_email_reminder)
while True:
schedule.run_pending()
time.sleep(1)
Here, send_email_reminder()
sends an email notification. Customize the sender address, recipient address, and SMTP server. This method allows easy automation of email reminder sending.
5. Reminders via Telegram
To send reminders via Telegram, you can use its API. In this example, we'll send a notification to a Telegram chat using requests
.
Setup:
-
Create a bot in Telegram via BotFather and get the
API_TOKEN
. -
Find your
CHAT_ID
by sending a message to the bot and getting the chat ID using the API.
import requests
import schedule
import time
def send_telegram_reminder():
api_token = "YOUR_API_TOKEN"
chat_id = "YOUR_CHAT_ID"
message = "Reminder: You have an important task today!"
url = f"https://api.telegram.org/bot{api_token}/sendMessage"
payload = {
"chat_id": chat_id,
"text": message
}
response = requests.post(url, data=payload)
if response.status_code == 200:
print("Reminder sent via Telegram.")
else:
print("Error sending Telegram reminder.")
# Schedule the reminder to be sent daily at 9:00 AM
schedule.every().day.at("09:00").do(send_telegram_reminder)
while True:
schedule.run_pending()
time.sleep(1)
Now, every day at 9:00 AM, the bot will send a notification to the specified Telegram chat.
6. Additional notification setup tips
- Error handling: Add error handling for sending notifications, such as checking the connection to the email server or Telegram.
-
Logging: Use the
logging
library to record reminder events. This will help track when reminders were actually sent. - Flexible settings: If you plan to use reminders in a project, create a function for dynamically setting the time and notification methods, so you can easily change the settings.
GO TO FULL VERSION