总有那么几天值得纪念

全文约1,284字 4分钟阅读

前几天写了个脚本玩具,想来自己也是一个念旧的人,用python写了一个用pushover提醒纪念日的脚本,自己玩玩看。

先上成果

玩具的用法

数据库(mysql 5.7)

iddatereasonnature
主键日期原因类别
 Navicat Premium Data Transfer

 Source Server         : 本地
 Source Server Type    : MySQL
 Source Server Version : 50722
 Source Host           : localhost:3306
 Source Schema         : mythings

 Target Server Type    : MySQL
 Target Server Version : 50722
 File Encoding         : 65001

 Date: 10/07/2019 22:07:54
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for everyday
-- ----------------------------
DROP TABLE IF EXISTS `everyday`;
CREATE TABLE `everyday`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `date` datetime(0) NULL DEFAULT NULL,
  `reason` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL,
  `nature` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 25 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

脚本代码(python3.6+)

app_token 和 user_key 需要自己在注册pushover自己获取。pushover官网点我

数据库的具体配置在全局变量模块里补充。

import http.client, urllib
import time
import warnings
warnings.filterwarnings("ignore")
import  pymysql
import requests
import datetime
import re



# 全局变量
myhost      = '127.0.0.1'
myport      = 3306
myuser      = ''
mypassword  = ''
mydb        = ''
mycharset = 'utf8'
num=['零','一','二','三','四','五','六','七','八','九']

# SELECT * FROM `everyday` WHERE date LIKE '%03-31%'
# select date_format(now(),'%y-%m-%d');

#第2步 查询那年今日的数据
def checkMyDays(m,d):

    # 数据库连接
    try:
        connect = pymysql.Connect(
            host    = myhost,
            port    = myport,
            user    = myuser,
            passwd  = mypassword,
            db      = mydb,
            charset = mycharset
        )
    except Exception as e:
        print("连接数据库失败",'错误是:', e)
        return 0
    #游标
    cursor = connect.cursor()
    month = str(m).zfill(2)
    day   = str(d).zfill(2)
    data ='%'+ '-' +'%'+ month + '-' + day + '%'
    # 数据
    sql = "SELECT DATE, REASON, NATURE FROM `everyday` WHERE date LIKE '%s'"
    #print(sql % data)

    #执行
    try:

        cursor.execute(sql % data)
        connect.commit()
    except Exception as  e:
        print("询那年今日的数据",'错误是:', e)
        return 0
    else:

        daysDATA = cursor.fetchall()
        # print(daysDATA)
        myresaon = []
        for i in range(0,len(daysDATA)):
            myresaon.append(daysDATA[i])

        print(getTimeDetail(),"第2步 查询所有" + str(m)+ '月' + str(d) + "日"+"数据成功")
        return myresaon
    finally:
        cursor.close()
        connect.close()


#第1步 获取今天日期的年月日
def getTime():
    now = time.strftime("%Y-%m-%d", time.localtime())
    y = datetime.datetime.now().year
    m = datetime.datetime.now().month
    d = datetime.datetime.now().day
    print(getTimeDetail(),"第1步 获取今天时间成功,时间为",y,m,d)
    return y,m,d



#获取当前机器的ip
def getIP():
    url = 'https://ipinfo.io'
    r_ip = requests.get(url)
    ip_json= r_ip.json()
    ip = ip_json['ip']

    ip = '当前ip:' + ip
    return ip


# 获取当前时间,精确到秒
def getTimeDetail():
    now = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime())
    return now


#第3步 推送
def myPushover2(y,m,d,myreason):
    app_token    = '应用密钥'
    user_key     = '用户密钥'
    msg = ''
    title = "那一年,那些年"

    deviceName = 'Phone6'
    sound = 'Intermission'
    if len(myreason) == 0:
        print("今天没事")
        return  0
    elif len(myreason) == 1:
        year1 = str(myreason[0][0])
        year2 = re.findall(r"[0-9]{4}",year1)#
        year3 = int(year2[0])
        singleReason = myreason[0][1]
        Difference_year = str(y - year3)
        msg = '今天是' + str(y) + '年'+ str(m)+ '月' + str(d) + '日, '+ str(year3)+ '的那一天。\n\n' + \
              singleReason +'\n'+'\n' \
              + Difference_year +'年过去了, 此时此刻的你有何感想,彼时彼刻的你又有什么要说的话吗?'
    # print(msg)
    elif len(myreason) >= 1:
        year3 = []
        singleReason = []
        Difference_year = []
        for i in range(0, len(myreason)):
            year1 = str(myreason[i][0])
            year2 = re.findall(r"[0-9]{4}",year1)#
            year3.append(int(year2[0]))
            singleReason.append(myreason[i][1])
            Difference_year.append(str(y - year3[i]))
        msg = '今天是' + str(y) + '年'+ str(m)+ '月' + str(d) + '日。那年今日发生了'+ str(len(myreason)) +'件事情'
        for i in range(0, len(myreason)):
            msg = msg + '\n'+ '\n'+ \
                  '第' + num[i + 1] + '件, ' + Difference_year[i] + '年前,也就是' +str(year3[i]) + '的那一天。\n' + \
                  singleReason[i] +'\n'



        msg = msg + '\n' + '\n' + '这么多年过去了, 此时此刻的你,有何感想,彼时彼刻的你,又有什么要说的话吗?'
    #print(msg)
    conn = http.client.HTTPSConnection("api.pushover.net:443")
    conn.request("POST", "/1/messages.json",
                 urllib.parse.urlencode({
                     "token": app_token,
                     "user": user_key,
                     "message": msg,
                     "title":title,
                     "sound":sound,
                     "device":deviceName
                 }), { "Content-type": "application/x-www-form-urlencoded" })
    conn.getresponse()

    print(getTimeDetail(),"第3步 推送到设备成功")
    return 0

# 全年测试函数
def testAllYear():
    for i in range(1,13):
        for j in  range(1, 32):
            print("\n")
            m = i
            d = j

            # 第2步 查询那年今日的数据
            myreason =  checkMyDays(m,d)
            myPushover2(y,m,d,myreason)


#主函数
if __name__ == "__main__":
    print("\n")

    # 第1步 获取今天日期的年月日
    y,m,d = getTime()

    m = 12
    d = 31
    # 第2步 查询那年今日的数据
    myreason =  checkMyDays(m,d)
    # 第3步 推送
    myPushover2(y,m,d,myreason)