怎样实现便签到期提醒脚本

wen 实用脚本 26

本文目录导读:

怎样实现便签到期提醒脚本

  1. 简单的命令行便签提醒(Python)
  2. 使用系统通知的版本(跨平台)
  3. 简单的 Shell 脚本版本(Linux/Mac)
  4. 使用说明
  5. 功能特点

我来帮你实现一个便签到期提醒脚本,这里提供几种不同的实现方式,从简单到复杂:

简单的命令行便签提醒(Python)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import json
import os
from datetime import datetime, timedelta
class NoteReminder:
    def __init__(self, notes_file="notes.json"):
        self.notes_file = notes_file
        self.notes = self.load_notes()
    def load_notes(self):
        """加载便签数据"""
        if os.path.exists(self.notes_file):
            with open(self.notes_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        return []
    def save_notes(self):
        """保存便签数据"""
        with open(self.notes_file, 'w', encoding='utf-8') as f:
            json.dump(self.notes, f, ensure_ascii=False, indent=2)
    def add_note(self, content, remind_time):
        """添加便签"""
        note = {
            'id': len(self.notes) + 1,
            'content': content,
            'remind_time': remind_time,
            'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'reminded': False
        }
        self.notes.append(note)
        self.save_notes()
        print(f"✅ 便签已添加: {content}")
        print(f"⏰ 提醒时间: {remind_time}")
    def check_reminders(self):
        """检查是否有到期的提醒"""
        current_time = datetime.now()
        for note in self.notes:
            if not note['reminded']:
                remind_datetime = datetime.strptime(note['remind_time'], '%Y-%m-%d %H:%M')
                if current_time >= remind_datetime:
                    print(f"\n🔔 提醒: {note['content']}")
                    print(f"⏰ 提醒时间: {note['remind_time']}")
                    note['reminded'] = True
                    self.save_notes()
        # 删除已提醒的过期便签(可选)
        self.cleanup_old_notes()
    def cleanup_old_notes(self, days=1):
        """清理旧的已提醒便签"""
        current_time = datetime.now()
        self.notes = [
            note for note in self.notes
            if not note['reminded'] or 
            (current_time - datetime.strptime(note['created_at'], '%Y-%m-%d %H:%M:%S')).days < days
        ]
        self.save_notes()
    def list_notes(self):
        """列出所有待提醒的便签"""
        pending_notes = [n for n in self.notes if not n['reminded']]
        if pending_notes:
            print("\n📝 待提醒便签列表:")
            for note in pending_notes:
                print(f"  ID: {note['id']} | 内容: {note['content'][:30]}... | 提醒: {note['remind_time']}")
        else:
            print("✅ 没有待提醒的便签")
def main():
    reminder = NoteReminder()
    while True:
        print("\n" + "="*40)
        print("   📋 便签提醒系统")
        print("="*40)
        print("1. 添加便签")
        print("2. 检查提醒")
        print("3. 查看便签列表")
        print("4. 删除便签")
        print("5. 退出")
        print("="*40)
        choice = input("请选择操作 (1-5): ").strip()
        if choice == '1':
            content = input("请输入便签内容: ").strip()
            if not content:
                print("❌ 内容不能为空")
                continue
            print("请输入提醒时间(格式: YYYY-MM-DD HH:MM)")
            remind_str = input(" 2024-01-15 14:30: ").strip()
            try:
                datetime.strptime(remind_str, '%Y-%m-%d %H:%M')
                reminder.add_note(content, remind_str)
            except ValueError:
                print("❌ 时间格式错误,请使用 YYYY-MM-DD HH:MM 格式")
        elif choice == '2':
            reminder.check_reminders()
            print("\n✅ 提醒检查完成")
        elif choice == '3':
            reminder.list_notes()
        elif choice == '4':
            reminder.list_notes()
            try:
                note_id = int(input("请输入要删除的便签ID: "))
                reminder.notes = [n for n in reminder.notes if n['id'] != note_id]
                reminder.save_notes()
                print(f"✅ 便签 {note_id} 已删除")
            except ValueError:
                print("❌ 无效的ID")
        elif choice == '5':
            print("👋 再见!")
            break
        else:
            print("❌ 无效选择,请重试")
        time.sleep(1)
if __name__ == "__main__":
    main()

使用系统通知的版本(跨平台)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import json
import os
import threading
import platform
from datetime import datetime, timedelta
class NotificationReminder:
    def __init__(self):
        self.notes = []
        self.running = False
    def send_notification(self, title, message):
        """发送系统通知"""
        system = platform.system()
        if system == "Windows":
            # Windows 使用 win10toast 或 ctypes
            try:
                from win10toast import ToastNotifier
                toaster = ToastNotifier()
                toaster.show_toast(title, message, duration=5)
            except ImportError:
                # 备用方案
                import ctypes
                ctypes.windll.user32.MessageBoxW(0, message, title, 0x40)
        elif system == "Darwin":  # macOS
            os.system(f"""
            osascript -e 'display notification "{message}" with title "{title}"'
            """)
        else:  # Linux
            try:
                os.system(f'notify-send "{title}" "{message}"')
            except:
                print(f"\n🔔 {title}: {message}")
    def add_note(self, content, remind_time, reminder_type="once"):
        """添加便签"""
        note = {
            'content': content,
            'remind_time': remind_time,
            'reminder_type': reminder_type,  # once, daily, weekly
            'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'reminded': False
        }
        self.notes.append(note)
        # 保存到文件
        with open('notes.json', 'w', encoding='utf-8') as f:
            json.dump(self.notes, f, ensure_ascii=False, indent=2)
        self.send_notification("便签已添加", f"将在 {remind_time} 提醒: {content}")
    def check_and_remind(self):
        """检查和发送提醒"""
        while self.running:
            current_time = datetime.now()
            for note in self.notes[:]:  # 使用切片创建副本
                remind_time = datetime.strptime(note['remind_time'], '%Y-%m-%d %H:%M')
                if current_time >= remind_time and not note.get('reminded', False):
                    self.send_notification("便签提醒", note['content'])
                    print(f"✅ 已发送提醒: {note['content']}")
                    if note['reminder_type'] == 'once':
                        note['reminded'] = True
                    elif note['reminder_type'] == 'daily':
                        # 设置为明天的同一时间
                        note['remind_time'] = (remind_time + timedelta(days=1)).strftime('%Y-%m-%d %H:%M')
            time.sleep(30)  # 每30秒检查一次
    def start(self):
        """启动提醒服务"""
        self.running = True
        thread = threading.Thread(target=self.check_and_remind, daemon=True)
        thread.start()
        print("✅ 提醒服务已启动")
        while True:
            print("\n" + "="*40)
            print("   📋 便签提醒系统")
            print("="*40)
            print("1. 添加便签")
            print("2. 查看便签列表")
            print("3. 退出")
            choice = input("\n请选择 (1-3): ").strip()
            if choice == '1':
                self.add_note_interactive()
            elif choice == '2':
                self.list_notes()
            elif choice == '3':
                self.running = False
                print("👋 再见!")
                break
    def add_note_interactive(self):
        """交互式添加便签"""
        print("\n📝 添加新便签")
        content = input("便签内容: ").strip()
        print("\n提醒类型:")
        print("1. 一次性")
        print("2. 每日重复")
        print("3. 每周重复")
        type_choice = input("请选择 (1-3): ").strip()
        reminder_types = {'1': 'once', '2': 'daily', '3': 'weekly'}
        reminder_type = reminder_types.get(type_choice, 'once')
        remind_str = input("提醒时间 (YYYY-MM-DD HH:MM): ").strip()
        try:
            datetime.strptime(remind_str, '%Y-%m-%d %H:%M')
            self.add_note(content, remind_str, reminder_type)
            print("✅ 便签添加成功!")
        except ValueError:
            print("❌ 时间格式错误")
    def list_notes(self):
        """列出所有便签"""
        if self.notes:
            print("\n📋 便签列表:")
            for i, note in enumerate(self.notes, 1):
                status = "✅ 已提醒" if note.get('reminded', False) else "⏳ 待提醒"
                print(f"{i}. [{status}] {note['content']}")
                print(f"   提醒时间: {note['remind_time']}")
        else:
            print("📭 暂无便签")
def main():
    reminder = NotificationReminder()
    reminder.start()
if __name__ == "__main__":
    main()

简单的 Shell 脚本版本(Linux/Mac)

#!/bin/bash
# 便签到期提醒脚本
NOTES_FILE="$HOME/.notes.txt"
# 初始化文件
init_notes() {
    if [ ! -f "$NOTES_FILE" ]; then
        touch "$NOTES_FILE"
    fi
}
# 添加便签
add_note() {
    echo "请输入便签内容:"
    read content
    echo "请输入提醒时间 (格式: YYYY-MM-DD HH:MM):"
    read remind_time
    echo "$remind_time|$content" >> "$NOTES_FILE"
    echo "✅ 便签已添加"
}
# 检查提醒
check_reminders() {
    local current_time=$(date "+%Y-%m-%d %H:%M")
    while IFS='|' read -r remind_time content; do
        if [[ "$current_time" > "$remind_time" ]] || [[ "$current_time" == "$remind_time" ]]; then
            echo -e "\n🔔 提醒: $content"
            echo "⏰ 时间: $remind_time"
            # 发送系统通知(如果支持)
            if command -v notify-send &> /dev/null; then
                notify-send "便签提醒" "$content"
            elif command -v osascript &> /dev/null; then
                osascript -e "display notification \"$content\" with title \"便签提醒\""
            fi
        fi
    done < "$NOTES_FILE"
}
# 主函数
main() {
    init_notes
    while true; do
        echo -e "\n================================"
        echo "   📋 便签提醒系统"
        echo "================================"
        echo "1. 添加便签"
        echo "2. 检查提醒"
        echo "3. 查看所有便签"
        echo "4. 退出"
        echo "================================"
        read -p "请选择 (1-4): " choice
        case $choice in
            1) add_note ;;
            2) check_reminders ;;
            3) cat "$NOTES_FILE" ;;
            4) echo "👋 再见!"; exit 0 ;;
            *) echo "❌ 无效选择" ;;
        esac
    done
}
main

使用说明

Python 脚本(推荐)

# 安装依赖(如果需要系统通知)
pip install win10toast  # Windows用户
# 运行脚本
python note_reminder.py

Shell 脚本

# 赋予执行权限
chmod +x note_reminder.sh
# 运行
./note_reminder.sh

功能特点

  1. 多种提醒方式:系统通知、命令行提示
  2. 持久化存储:便签保存在本地文件
  3. 定时检查:自动检查到期的提醒
  4. 重复提醒:支持一次性、每日、每周重复
  5. 跨平台支持:Windows、macOS、Linux

你可以根据自己的需求选择适合的版本,或者在此基础上添加更多的功能,

  • 邮件提醒
  • 微信提醒
  • 任务优先级
  • 分类管理

抱歉,评论功能暂时关闭!