1. 알림 메커니즘 구현
datetime 및 timedelta 모듈 사용
어떤 이벤트까지 남은 시간을 계산해서 알람을 설정할 때가 있어. 이때 timedelta가 유용하게 쓰여:
Python
from datetime import datetime, timedelta
# 알람 시간 계산
meeting_time = datetime(2023, 10, 30, 15, 0, 0)
reminder_time = meeting_time - timedelta(minutes=30)
print(f"알림을 보내야 하는 시간: {reminder_time}")
콘솔을 통한 간단한 알림
첫 단계로 간단히 콘솔 알림을 만들어보자. 물론 스마트폰의 push 알림처럼 "멋지진" 않겠지만, 처음엔 이 정도도 괜찮아.
Python
import time
def simple_reminder(message, delay):
print(f"{delay}초 후 알림이 올 예정이에요...")
time.sleep(delay)
print(f"알림: {message}")
simple_reminder("회의 시간이에요!", 10)
2. 주기적인 알림을 위한 schedule 사용
알림을 반복해야 할 때는 schedule이 큰 도움이 돼. 일일 또는 주간 같은 다양한 간격을 설정할 수 있어:
Python
import schedule
import time
def meeting_reminder():
print("알림: 곧 회의가 있어요!")
# 매일 오후 2시 30분에 알림 설정
schedule.every().day.at("14:30").do(meeting_reminder)
while True:
schedule.run_pending()
time.sleep(1)
3. plyer 라이브러리를 사용한 시스템 알림
더 "진짜 같은" 알림을 원할 땐 plyer 라이브러리를 사용해서 시스템 알림을 보낼 수 있어:
Python
from plyer import notification
import time
def plyer_notification(title, message):
notification.notify(
title=title,
message=message,
app_name='Python Reminder',
timeout=10
)
# 사용 예시
plyer_notification("알림!", "회의 시간이에요.")
notification.notify() 함수는 운영 체제 표준 알림을 표시해줘.
4. 이메일로 알림 보내기
이메일로 알림을 보내려면 Python에서 smtplib 모듈을 사용하면 돼. 다음 예시는 SMTP 서버를 사용해서 이메일로 알림을 보내는 방법이야.
Python
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 = "작업 알림"
body = "이것은 자동 알림입니다. 오늘 작업을 완료하는 것을 잊지 마세요."
# 메시지 생성
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = sender
msg["To"] = receiver
# SMTP 서버에 연결하여 이메일 전송
with smtplib.SMTP("smtp.example.com", 587) as server:
server.starttls()
server.login(sender, "your_password")
server.sendmail(sender, receiver, msg.as_string())
print("이메일로 알림이 전송되었습니다.")
# 매일 오전 8시 30분에 알림 전송
schedule.every().day.at("08:30").do(send_email_reminder)
while True:
schedule.run_pending()
time.sleep(1)
여기서 send_email_reminder()는 이메일로 알림을 보냅니다. 발신자, 수신자 주소와 SMTP 서버를 설정하세요. 이 방법은 이메일 알림 전송을 자동화하는 데 유용해.
5. Telegram으로 알림 전송
Telegram API를 사용하여 알림을 보내는 방법도 있어. 이 예시는 requests를 사용하여 Telegram 채팅에 알림을 보내는 방법을 보여줘.
설정:
- BotFather를 통해 Telegram 봇을 생성하고
API_TOKEN을 가져오세요. - 봇에 메시지를 보내고 API를 통해 채팅 ID
CHAT_ID를 확인하세요.
Python
import requests
import schedule
import time
def send_telegram_reminder():
api_token = "YOUR_API_TOKEN"
chat_id = "YOUR_CHAT_ID"
message = "알림: 오늘 중요한 작업이 있습니다!"
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("Telegram을 통해 알림이 전송되었습니다.")
else:
print("Telegram 알림 전송 오류 발생.")
# 매일 오전 9시에 알림 전송
schedule.every().day.at("09:00").do(send_telegram_reminder)
while True:
schedule.run_pending()
time.sleep(1)
이제 매일 오전 9시에 봇이 Telegram 채팅에 알림을 보내게 돼.
6. 알림 설정에 대한 추가 팁
- 오류 처리: 알림 전송 시 오류가 발생하지 않도록 이메일 서버나 Telegram 연결을 확인하는 등의 오류 처리를 추가하세요.
- 로깅:
logging라이브러리를 사용하여 알림 이벤트를 기록하세요. 이를 통해 실제 알림이 언제 전송되었는지 확인할 수 있어요. - 설정 유연성: 프로젝트에서 알림을 사용할 계획이라면 알림 시간과 방식을 동적으로 설정할 수 있는 기능을 만들어서 설정을 쉽게 변경할 수 있도록 하세요.
GO TO FULL VERSION