From 88f66f5f4efb94ea0229a01ee6fd029917f91086 Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 21:57:16 +0800 Subject: [PATCH 01/16] Update send_love.yml --- .github/workflows/send_love.yml | 36 ++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/.github/workflows/send_love.yml b/.github/workflows/send_love.yml index 09648dd..125b14a 100644 --- a/.github/workflows/send_love.yml +++ b/.github/workflows/send_love.yml @@ -1,22 +1,48 @@ name: CI on: schedule: - - cron: "5 0 * * *" + # 每天早上7:40运行 + - cron: "40 7 * * *" + # 每天下午5:00运行 + - cron: "0 17 * * *" push: branches: [ "main" ] jobs: - build: + send-morning-message: runs-on: ubuntu-latest - steps: + steps: + - name: Checkout repository - uses: actions/checkout@v3 + - name: Set up Python 3.9 uses: actions/setup-python@v2 with: python-version: 3.9 + - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - - name: send msg + + - name: Run morning message script run: | - python send_love_msg.py + python send_morning_message.py + send-evening-message: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: 3.9 + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + + - name: Run evening message script + run: | + python send_evening_message.py From ea796f4c53fb8d8837290409e4fc999cb6ec6cb8 Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 22:01:05 +0800 Subject: [PATCH 02/16] Create send_evening_message.py --- send_evening_message.py | 81 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 send_evening_message.py diff --git a/send_evening_message.py b/send_evening_message.py new file mode 100644 index 0000000..6fb81b1 --- /dev/null +++ b/send_evening_message.py @@ -0,0 +1,81 @@ +import json +from datetime import datetime +import pytz +import requests +from config import loadConfig + +# Load configuration +config = loadConfig("config.yaml") +qywxWebhookKey = config.weChatWork.webhookKey +wxpushAppToken = config.wxPusher.appToken +wxpushTopicIds = config.wxPusher.topicIds +city = config.weather.city +monthOfBirthday = config.lover.monthOfBirthday +dayOfBirthday = config.lover.dayOfBirthday +expressLoveTimestamp = config.lover.expressLoveTimestamp +meetingTimestamp = config.lover.meetingTimestamp +weatherApiKey = config.weather.apiKey + +def getMsgHeader(): + tz = pytz.timezone("Asia/Shanghai") + dt = datetime.now(tz) + return '今天是 {}'.format(dt.strftime("%Y-%m-%d %A")) + +class Weather: + # 同样的Weather类实现... + +def getWeather() -> Weather: + # 同样的getWeather函数实现... + +def getMeetingDay(): + # 同样的getMeetingDay函数实现... + +def getBirthDayOfLover(): + # 同样的getBirthDayOfLover函数实现... + +def getExpressLoveDay(): + # 同样的getExpressLoveDay函数实现... + +class DailyWord: + # 同样的DailyWord类实现... + +def getDailyWord() -> DailyWord: + # 同样的getDailyWord函数实现... + +def sendAlarmMsg(mdTex): + wechatwork(mdTex) + +def wechatwork(tex): + # 同样的wechatwork函数实现... + +def wxPusher(tex): + # 同样的wxPusher函数实现... + +if __name__ == "__main__": + h = getMsgHeader() + w = getWeather() + bd = getBirthDayOfLover() + md = getMeetingDay() + ed = getExpressLoveDay() + dw = getDailyWord() + + # 企业微信 + tex1 = ( + '{}\n> 今天是我们相爱的 {} 天({})\n' + '我们已经相遇 {} 天({})\n' + '距离你的生日还有 {} 天' + ).format( + h, + ed, + datetime.fromtimestamp(expressLoveTimestamp, tz=pytz.utc) + .astimezone(pytz.timezone("Asia/Shanghai")) + .strftime("%Y-%m-%d"), + md, + datetime.fromtimestamp(meetingTimestamp, tz=pytz.utc) + .astimezone(pytz.timezone("Asia/Shanghai")) + .strftime("%Y-%m-%d"), + bd, + ) + + wechatwork(tex1) + sendDailyWordToWechatWork(dw) From d8e239adf26246beca695070984d4f7f39dc8b08 Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 22:03:09 +0800 Subject: [PATCH 03/16] Update send_evening_message.py --- send_evening_message.py | 262 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 252 insertions(+), 10 deletions(-) diff --git a/send_evening_message.py b/send_evening_message.py index 6fb81b1..3cba800 100644 --- a/send_evening_message.py +++ b/send_evening_message.py @@ -1,7 +1,9 @@ import json from datetime import datetime + import pytz import requests + from config import loadConfig # Load configuration @@ -16,40 +18,248 @@ meetingTimestamp = config.lover.meetingTimestamp weatherApiKey = config.weather.apiKey + def getMsgHeader(): tz = pytz.timezone("Asia/Shanghai") dt = datetime.now(tz) - return '今天是 {}'.format(dt.strftime("%Y-%m-%d %A")) + h = '今天是 {}'.format(dt.strftime("%Y-%m-%d %A")) + return h + + +def getMsgHeaderToWechat(): + tz = pytz.timezone("Asia/Shanghai") + dt = datetime.now(tz) + h = '今天是 {}'.format(dt.strftime("%Y-%m-%d %A")) + return h + class Weather: - # 同样的Weather类实现... + def __init__(self): + self.city = "" + self.adcode = "" + self.province = "" + self.reporttime = "" + self.date = "" + self.week = "" + self.dayweather = "" + self.nightweather = "" + self.daytemp = "" + self.nighttemp = "" + self.daywind = "" + self.nightwind = "" + self.daypower = "" + self.nightpower = "" + + def isValide(self) -> bool: + return self.city != "" + + def jsonDecode(self, jsonTex): + self.city = jsonTex["city"] + self.adcode = jsonTex["adcode"] + self.province = jsonTex["province"] + self.reporttime = jsonTex["reporttime"] + casts = jsonTex["casts"][0] + self.date = casts["date"] + self.week = casts["week"] + self.dayweather = casts["dayweather"] + self.nightweather = casts["nightweather"] + self.daytemp = casts["daytemp"] + self.nighttemp = casts["nighttemp"] + self.daywind = casts["daywind"] + self.nightwind = casts["nightwind"] + self.daypower = casts["daypower"] + self.nightpower = casts["nightpower"] + + def getWeatherTextToWechatWork(self): + tex = '武汉天气\n > {}, 白天温度: {} ~ 晚上温度: {}\n白天风力:{}-{},晚上风力:{}-{}。'.format( + self.dayweather, + self.daytemp, + self.nighttemp, + self.daypower, + self.daywind, + self.nightpower, + self.nightwind, + ) + return tex + + def getWeatherTextToWechat(self): + tex = '
武汉天气
{}, 白天温度: {} ~ 晚上温度: {}, 白天风力:{}-{},晚上风力:{}-{}。'.format( + self.dayweather, + self.daytemp, + self.nighttemp, + self.daypower, + self.daywind, + self.nightpower, + self.nightwind, + ) + return tex + def getWeather() -> Weather: - # 同样的getWeather函数实现... + url = "https://restapi.amap.com/v3/weather/weatherInfo" + params = { + "city": city, + "extensions": "all", + "key": weatherApiKey, + } + + try: + response = requests.get(url, params=params) + response.raise_for_status() # 检查请求是否成功 + data = response.json() + + if data.get("status") != "1": + raise ValueError(f"API Error: {data.get('info')}") + + forecasts_data = data.get("forecasts", []) + if not forecasts_data: + raise ValueError("No forecasts data available.") + + forecast = forecasts_data[0] + weather = Weather() + weather.jsonDecode(forecast) + + return weather + + except requests.RequestException as e: + print(f"Request error: {e}") + except ValueError as e: + print(f"Value error: {e}") + except Exception as e: + print(f"Unexpected error: {e}") + + return Weather() # 返回一个无效的 Weather 对象 + def getMeetingDay(): - # 同样的getMeetingDay函数实现... + tz = pytz.timezone("Asia/Shanghai") + now = datetime.now(tz) + day = int((now.timestamp() - meetingTimestamp) / (24 * 60 * 60)) + print(day) + print("相遇的:", day) + return day + def getBirthDayOfLover(): - # 同样的getBirthDayOfLover函数实现... + tz = pytz.timezone("Asia/Shanghai") + yearNow = datetime.now(tz) + dt = datetime(yearNow.year, yearNow.month, yearNow.day) + # 判断今年的生日是否已经过去 + birthday = datetime(yearNow.year, monthOfBirthday, dayOfBirthday) + if birthday.timestamp() < yearNow.timestamp(): + # 下一年的生日 + birthday = datetime(birthday.year + 1, monthOfBirthday, dayOfBirthday) + day = int((birthday.timestamp() - dt.timestamp()) / (24 * 60 * 60)) + print("生日:", day) + return day + def getExpressLoveDay(): - # 同样的getExpressLoveDay函数实现... + # unixTimeStamp = 1599148800 + tz = pytz.timezone("Asia/Shanghai") + now = datetime.now(tz) + day = int((now.timestamp() - expressLoveTimestamp) / (24 * 60 * 60)) + print(day) + print("相爱的天:", day) + return day + class DailyWord: - # 同样的DailyWord类实现... + def __init__(self): + self.sid = "" + self.note = "" + self.content = "" + self.pic = "" + + def isValide(self) -> bool: + return self.sid != "" + + def getDailyWordHtml(self) -> str: + return '
每日一句
{}
{}
'.format( + self.content, self.note, self.pic + ) + def getDailyWord() -> DailyWord: - # 同样的getDailyWord函数实现... + url = "http://open.iciba.com/dsapi" + r = requests.get(url) + r.encoding = "utf-8" + result = r.json() + dw = DailyWord() + if result.get("sid"): + dw.sid = result["sid"] + dw.note = result["note"] + dw.content = result["content"] + dw.pic = result["fenxiang_img"] + return dw + + +def sendDailyWordToWechatWork(dw: DailyWord): + if dw.isValide(): + webhook = ( + f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={qywxWebhookKey}" + ) + header = {"Content-Type": "application/json", "Charset": "UTF-8"} + message = { + "msgtype": "news", + "news": { + "articles": [ + { + "title": "每日一句", + "description": dw.content, + "url": dw.pic, + "picurl": dw.pic, + } + ] + }, + } + message_json = json.dumps(message) + requests.post(url=webhook, data=message_json, headers=header) + return + def sendAlarmMsg(mdTex): wechatwork(mdTex) + def wechatwork(tex): - # 同样的wechatwork函数实现... + webhook = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={qywxWebhookKey}" + header = {"Content-Type": "application/json", "Charset": "UTF-8"} + message = {"msgtype": "markdown", "markdown": {"content": tex}} + print(f"wechat send msg, key:{qywxWebhookKey}") + print(message) + message_json = json.dumps(message) + try: + requests.post(url=webhook, data=message_json, headers=header) + except requests.exceptions.RequestException as e: + print("unable to connect to wechat server, err:", e) + except Exception as e2: + print("send message to wechat server, err:", e2) + sendAlarmMsg(str(e2)) + def wxPusher(tex): - # 同样的wxPusher函数实现... + url = "http://wxpusher.zjiecode.com/api/send/message" + header = {"Content-Type": "application/json", "Charset": "UTF-8"} + message = { + "appToken": wxpushAppToken, + "content": tex, + "summary": "相爱一生", + "contentType": 2, + "topicIds": wxpushTopicIds, + "url": "http://wxpusher.zjiecode.com", + } + message_json = json.dumps(message) + try: + info = requests.post(url=url, data=message_json, headers=header) + print(info.text) + except requests.exceptions.RequestException as e: + print("unable to connect to wx, err:", e) + sendAlarmMsg(str(e)) + except Exception as e: + print("send message to wx, err:", e) + sendAlarmMsg(str(e)) + if __name__ == "__main__": h = getMsgHeader() @@ -60,6 +270,14 @@ def wxPusher(tex): dw = getDailyWord() # 企业微信 + w1 = w.getWeatherTextToWechatWork() + # tex1 = '{}\n> 今天是我们相爱的 {} 天\n我们已经相遇 {} + # 天({})\n距离你的生日还有 {} 天\n\n{}'.format( + # h, ed, md,datetime.utcfromtimestamp(meetingTimestamp).strftime('%Y-%m-%d %H:%M:%S') , bd, w1 + # ) + + # 一行代码完成转换和格式化,并插入到原始字符串中 + tex1 = ( '{}\n> 今天是我们相爱的 {} 天({})\n' '我们已经相遇 {} 天({})\n' @@ -79,3 +297,27 @@ def wxPusher(tex): wechatwork(tex1) sendDailyWordToWechatWork(dw) + + # wxpusher + h2 = getMsgHeaderToWechat() + w2 = w.getWeatherTextToWechat() + dw2 = dw.getDailyWordHtml() + tex2 = ( + '{}
今天是我们相爱的 {} 天({})
' + '我们已经相遇{}天({})
' + '距离你的生日还有 {}

{}
{}' + ).format( + h2, + ed, + datetime.fromtimestamp(expressLoveTimestamp, tz=pytz.utc) + .astimezone(pytz.timezone("Asia/Shanghai")) + .strftime("%Y-%m-%d"), + md, + datetime.fromtimestamp(meetingTimestamp, tz=pytz.utc) + .astimezone(pytz.timezone("Asia/Shanghai")) + .strftime("%Y-%m-%d"), + bd, + w2, + dw2, + ) + wxPusher(tex2) From abdb39cda4bfd4b03698017babce8b2be67a109a Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 22:03:47 +0800 Subject: [PATCH 04/16] Create send_morning_message.py --- send_morning_message.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 send_morning_message.py diff --git a/send_morning_message.py b/send_morning_message.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/send_morning_message.py @@ -0,0 +1 @@ + From 7eed5cec48acd7dc2e4cbe9503e2f25140462e19 Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 22:04:18 +0800 Subject: [PATCH 05/16] Update send_morning_message.py --- send_morning_message.py | 322 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 322 insertions(+) diff --git a/send_morning_message.py b/send_morning_message.py index 8b13789..3cba800 100644 --- a/send_morning_message.py +++ b/send_morning_message.py @@ -1 +1,323 @@ +import json +from datetime import datetime +import pytz +import requests + +from config import loadConfig + +# Load configuration +config = loadConfig("config.yaml") +qywxWebhookKey = config.weChatWork.webhookKey +wxpushAppToken = config.wxPusher.appToken +wxpushTopicIds = config.wxPusher.topicIds +city = config.weather.city +monthOfBirthday = config.lover.monthOfBirthday +dayOfBirthday = config.lover.dayOfBirthday +expressLoveTimestamp = config.lover.expressLoveTimestamp +meetingTimestamp = config.lover.meetingTimestamp +weatherApiKey = config.weather.apiKey + + +def getMsgHeader(): + tz = pytz.timezone("Asia/Shanghai") + dt = datetime.now(tz) + h = '今天是 {}'.format(dt.strftime("%Y-%m-%d %A")) + return h + + +def getMsgHeaderToWechat(): + tz = pytz.timezone("Asia/Shanghai") + dt = datetime.now(tz) + h = '今天是 {}'.format(dt.strftime("%Y-%m-%d %A")) + return h + + +class Weather: + def __init__(self): + self.city = "" + self.adcode = "" + self.province = "" + self.reporttime = "" + self.date = "" + self.week = "" + self.dayweather = "" + self.nightweather = "" + self.daytemp = "" + self.nighttemp = "" + self.daywind = "" + self.nightwind = "" + self.daypower = "" + self.nightpower = "" + + def isValide(self) -> bool: + return self.city != "" + + def jsonDecode(self, jsonTex): + self.city = jsonTex["city"] + self.adcode = jsonTex["adcode"] + self.province = jsonTex["province"] + self.reporttime = jsonTex["reporttime"] + casts = jsonTex["casts"][0] + self.date = casts["date"] + self.week = casts["week"] + self.dayweather = casts["dayweather"] + self.nightweather = casts["nightweather"] + self.daytemp = casts["daytemp"] + self.nighttemp = casts["nighttemp"] + self.daywind = casts["daywind"] + self.nightwind = casts["nightwind"] + self.daypower = casts["daypower"] + self.nightpower = casts["nightpower"] + + def getWeatherTextToWechatWork(self): + tex = '武汉天气\n > {}, 白天温度: {} ~ 晚上温度: {}\n白天风力:{}-{},晚上风力:{}-{}。'.format( + self.dayweather, + self.daytemp, + self.nighttemp, + self.daypower, + self.daywind, + self.nightpower, + self.nightwind, + ) + return tex + + def getWeatherTextToWechat(self): + tex = '
武汉天气
{}, 白天温度: {} ~ 晚上温度: {}, 白天风力:{}-{},晚上风力:{}-{}。'.format( + self.dayweather, + self.daytemp, + self.nighttemp, + self.daypower, + self.daywind, + self.nightpower, + self.nightwind, + ) + return tex + + +def getWeather() -> Weather: + url = "https://restapi.amap.com/v3/weather/weatherInfo" + params = { + "city": city, + "extensions": "all", + "key": weatherApiKey, + } + + try: + response = requests.get(url, params=params) + response.raise_for_status() # 检查请求是否成功 + data = response.json() + + if data.get("status") != "1": + raise ValueError(f"API Error: {data.get('info')}") + + forecasts_data = data.get("forecasts", []) + if not forecasts_data: + raise ValueError("No forecasts data available.") + + forecast = forecasts_data[0] + weather = Weather() + weather.jsonDecode(forecast) + + return weather + + except requests.RequestException as e: + print(f"Request error: {e}") + except ValueError as e: + print(f"Value error: {e}") + except Exception as e: + print(f"Unexpected error: {e}") + + return Weather() # 返回一个无效的 Weather 对象 + + +def getMeetingDay(): + tz = pytz.timezone("Asia/Shanghai") + now = datetime.now(tz) + day = int((now.timestamp() - meetingTimestamp) / (24 * 60 * 60)) + print(day) + print("相遇的:", day) + return day + + +def getBirthDayOfLover(): + tz = pytz.timezone("Asia/Shanghai") + yearNow = datetime.now(tz) + dt = datetime(yearNow.year, yearNow.month, yearNow.day) + # 判断今年的生日是否已经过去 + birthday = datetime(yearNow.year, monthOfBirthday, dayOfBirthday) + if birthday.timestamp() < yearNow.timestamp(): + # 下一年的生日 + birthday = datetime(birthday.year + 1, monthOfBirthday, dayOfBirthday) + day = int((birthday.timestamp() - dt.timestamp()) / (24 * 60 * 60)) + print("生日:", day) + return day + + +def getExpressLoveDay(): + # unixTimeStamp = 1599148800 + tz = pytz.timezone("Asia/Shanghai") + now = datetime.now(tz) + day = int((now.timestamp() - expressLoveTimestamp) / (24 * 60 * 60)) + print(day) + print("相爱的天:", day) + return day + + +class DailyWord: + def __init__(self): + self.sid = "" + self.note = "" + self.content = "" + self.pic = "" + + def isValide(self) -> bool: + return self.sid != "" + + def getDailyWordHtml(self) -> str: + return '
每日一句
{}
{}
'.format( + self.content, self.note, self.pic + ) + + +def getDailyWord() -> DailyWord: + url = "http://open.iciba.com/dsapi" + r = requests.get(url) + r.encoding = "utf-8" + result = r.json() + dw = DailyWord() + if result.get("sid"): + dw.sid = result["sid"] + dw.note = result["note"] + dw.content = result["content"] + dw.pic = result["fenxiang_img"] + return dw + + +def sendDailyWordToWechatWork(dw: DailyWord): + if dw.isValide(): + webhook = ( + f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={qywxWebhookKey}" + ) + header = {"Content-Type": "application/json", "Charset": "UTF-8"} + message = { + "msgtype": "news", + "news": { + "articles": [ + { + "title": "每日一句", + "description": dw.content, + "url": dw.pic, + "picurl": dw.pic, + } + ] + }, + } + message_json = json.dumps(message) + requests.post(url=webhook, data=message_json, headers=header) + return + + +def sendAlarmMsg(mdTex): + wechatwork(mdTex) + + +def wechatwork(tex): + webhook = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={qywxWebhookKey}" + header = {"Content-Type": "application/json", "Charset": "UTF-8"} + message = {"msgtype": "markdown", "markdown": {"content": tex}} + print(f"wechat send msg, key:{qywxWebhookKey}") + print(message) + message_json = json.dumps(message) + try: + requests.post(url=webhook, data=message_json, headers=header) + except requests.exceptions.RequestException as e: + print("unable to connect to wechat server, err:", e) + except Exception as e2: + print("send message to wechat server, err:", e2) + sendAlarmMsg(str(e2)) + + +def wxPusher(tex): + url = "http://wxpusher.zjiecode.com/api/send/message" + header = {"Content-Type": "application/json", "Charset": "UTF-8"} + message = { + "appToken": wxpushAppToken, + "content": tex, + "summary": "相爱一生", + "contentType": 2, + "topicIds": wxpushTopicIds, + "url": "http://wxpusher.zjiecode.com", + } + message_json = json.dumps(message) + try: + info = requests.post(url=url, data=message_json, headers=header) + print(info.text) + except requests.exceptions.RequestException as e: + print("unable to connect to wx, err:", e) + sendAlarmMsg(str(e)) + except Exception as e: + print("send message to wx, err:", e) + sendAlarmMsg(str(e)) + + +if __name__ == "__main__": + h = getMsgHeader() + w = getWeather() + bd = getBirthDayOfLover() + md = getMeetingDay() + ed = getExpressLoveDay() + dw = getDailyWord() + + # 企业微信 + w1 = w.getWeatherTextToWechatWork() + # tex1 = '{}\n> 今天是我们相爱的 {} 天\n我们已经相遇 {} + # 天({})\n距离你的生日还有 {} 天\n\n{}'.format( + # h, ed, md,datetime.utcfromtimestamp(meetingTimestamp).strftime('%Y-%m-%d %H:%M:%S') , bd, w1 + # ) + + # 一行代码完成转换和格式化,并插入到原始字符串中 + + tex1 = ( + '{}\n> 今天是我们相爱的 {} 天({})\n' + '我们已经相遇 {} 天({})\n' + '距离你的生日还有 {} 天' + ).format( + h, + ed, + datetime.fromtimestamp(expressLoveTimestamp, tz=pytz.utc) + .astimezone(pytz.timezone("Asia/Shanghai")) + .strftime("%Y-%m-%d"), + md, + datetime.fromtimestamp(meetingTimestamp, tz=pytz.utc) + .astimezone(pytz.timezone("Asia/Shanghai")) + .strftime("%Y-%m-%d"), + bd, + ) + + wechatwork(tex1) + sendDailyWordToWechatWork(dw) + + # wxpusher + h2 = getMsgHeaderToWechat() + w2 = w.getWeatherTextToWechat() + dw2 = dw.getDailyWordHtml() + tex2 = ( + '{}
今天是我们相爱的 {} 天({})
' + '我们已经相遇{}天({})
' + '距离你的生日还有 {}

{}
{}' + ).format( + h2, + ed, + datetime.fromtimestamp(expressLoveTimestamp, tz=pytz.utc) + .astimezone(pytz.timezone("Asia/Shanghai")) + .strftime("%Y-%m-%d"), + md, + datetime.fromtimestamp(meetingTimestamp, tz=pytz.utc) + .astimezone(pytz.timezone("Asia/Shanghai")) + .strftime("%Y-%m-%d"), + bd, + w2, + dw2, + ) + wxPusher(tex2) From 3e825af45d83e5a6b0831e4ec64fc9af8d98ecaa Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 22:22:20 +0800 Subject: [PATCH 06/16] Update send_morning_message.py --- send_morning_message.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/send_morning_message.py b/send_morning_message.py index 3cba800..1f0f78f 100644 --- a/send_morning_message.py +++ b/send_morning_message.py @@ -71,7 +71,7 @@ def jsonDecode(self, jsonTex): self.nightpower = casts["nightpower"] def getWeatherTextToWechatWork(self): - tex = '武汉天气\n > {}, 白天温度: {} ~ 晚上温度: {}\n白天风力:{}-{},晚上风力:{}-{}。'.format( + tex = '西安天气\n > {}, 白天温度: {} ~ 晚上温度: {}\n白天风力:{}-{},晚上风力:{}-{}。'.format( self.dayweather, self.daytemp, self.nighttemp, @@ -83,7 +83,7 @@ def getWeatherTextToWechatWork(self): return tex def getWeatherTextToWechat(self): - tex = '
武汉天气
{}, 白天温度: {} ~ 晚上温度: {}, 白天风力:{}-{},晚上风力:{}-{}。'.format( + tex = '
西安天气
{}, 白天温度: {} ~ 晚上温度: {}, 白天风力:{}-{},晚上风力:{}-{}。'.format( self.dayweather, self.daytemp, self.nighttemp, @@ -268,6 +268,14 @@ def wxPusher(tex): md = getMeetingDay() ed = getExpressLoveDay() dw = getDailyWord() + days_until_end = getDaysUntil("2024-10-27") + + # 新增的提醒内容 + medication_reminder = ( + '记得按时吃药哦,再坚持 {} 天就好了:' + '早晨空腹:雷贝拉唑 * 1,枸酸秘钾 * 2;' + '饭后半小时:阿莫西林 * 4,克拉霉素 * 2。' + ).format(days_until_end) # 企业微信 w1 = w.getWeatherTextToWechatWork() From 5adc8a9a10bfb7ebb040088a483a7aa5689236ed Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 22:26:03 +0800 Subject: [PATCH 07/16] Update send_morning_message.py --- send_morning_message.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/send_morning_message.py b/send_morning_message.py index 1f0f78f..9cf7355 100644 --- a/send_morning_message.py +++ b/send_morning_message.py @@ -272,7 +272,7 @@ def wxPusher(tex): # 新增的提醒内容 medication_reminder = ( - '记得按时吃药哦,再坚持 {} 天就好了:' + '宝宝记得按时吃药哦,再坚持 {} 天就好拉:' '早晨空腹:雷贝拉唑 * 1,枸酸秘钾 * 2;' '饭后半小时:阿莫西林 * 4,克拉霉素 * 2。' ).format(days_until_end) @@ -327,5 +327,6 @@ def wxPusher(tex): bd, w2, dw2, + medication_reminder ) wxPusher(tex2) From 16386dbdb2ba7cb4beec8dc281b9ae0ab84feaaa Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 22:32:12 +0800 Subject: [PATCH 08/16] Update send_evening_message.py --- send_evening_message.py | 284 +++------------------------------------- 1 file changed, 16 insertions(+), 268 deletions(-) diff --git a/send_evening_message.py b/send_evening_message.py index 3cba800..2fb1257 100644 --- a/send_evening_message.py +++ b/send_evening_message.py @@ -1,9 +1,7 @@ import json -from datetime import datetime - +from datetime import datetime, timedelta import pytz import requests - from config import loadConfig # Load configuration @@ -11,223 +9,20 @@ qywxWebhookKey = config.weChatWork.webhookKey wxpushAppToken = config.wxPusher.appToken wxpushTopicIds = config.wxPusher.topicIds -city = config.weather.city -monthOfBirthday = config.lover.monthOfBirthday -dayOfBirthday = config.lover.dayOfBirthday -expressLoveTimestamp = config.lover.expressLoveTimestamp -meetingTimestamp = config.lover.meetingTimestamp -weatherApiKey = config.weather.apiKey - -def getMsgHeader(): - tz = pytz.timezone("Asia/Shanghai") - dt = datetime.now(tz) - h = '今天是 {}'.format(dt.strftime("%Y-%m-%d %A")) - return h - - -def getMsgHeaderToWechat(): - tz = pytz.timezone("Asia/Shanghai") - dt = datetime.now(tz) - h = '今天是 {}'.format(dt.strftime("%Y-%m-%d %A")) - return h - - -class Weather: - def __init__(self): - self.city = "" - self.adcode = "" - self.province = "" - self.reporttime = "" - self.date = "" - self.week = "" - self.dayweather = "" - self.nightweather = "" - self.daytemp = "" - self.nighttemp = "" - self.daywind = "" - self.nightwind = "" - self.daypower = "" - self.nightpower = "" - - def isValide(self) -> bool: - return self.city != "" - - def jsonDecode(self, jsonTex): - self.city = jsonTex["city"] - self.adcode = jsonTex["adcode"] - self.province = jsonTex["province"] - self.reporttime = jsonTex["reporttime"] - casts = jsonTex["casts"][0] - self.date = casts["date"] - self.week = casts["week"] - self.dayweather = casts["dayweather"] - self.nightweather = casts["nightweather"] - self.daytemp = casts["daytemp"] - self.nighttemp = casts["nighttemp"] - self.daywind = casts["daywind"] - self.nightwind = casts["nightwind"] - self.daypower = casts["daypower"] - self.nightpower = casts["nightpower"] - - def getWeatherTextToWechatWork(self): - tex = '武汉天气\n > {}, 白天温度: {} ~ 晚上温度: {}\n白天风力:{}-{},晚上风力:{}-{}。'.format( - self.dayweather, - self.daytemp, - self.nighttemp, - self.daypower, - self.daywind, - self.nightpower, - self.nightwind, - ) - return tex - - def getWeatherTextToWechat(self): - tex = '
武汉天气
{}, 白天温度: {} ~ 晚上温度: {}, 白天风力:{}-{},晚上风力:{}-{}。'.format( - self.dayweather, - self.daytemp, - self.nighttemp, - self.daypower, - self.daywind, - self.nightpower, - self.nightwind, - ) - return tex - - -def getWeather() -> Weather: - url = "https://restapi.amap.com/v3/weather/weatherInfo" - params = { - "city": city, - "extensions": "all", - "key": weatherApiKey, - } - - try: - response = requests.get(url, params=params) - response.raise_for_status() # 检查请求是否成功 - data = response.json() - - if data.get("status") != "1": - raise ValueError(f"API Error: {data.get('info')}") - - forecasts_data = data.get("forecasts", []) - if not forecasts_data: - raise ValueError("No forecasts data available.") - - forecast = forecasts_data[0] - weather = Weather() - weather.jsonDecode(forecast) - - return weather - - except requests.RequestException as e: - print(f"Request error: {e}") - except ValueError as e: - print(f"Value error: {e}") - except Exception as e: - print(f"Unexpected error: {e}") - - return Weather() # 返回一个无效的 Weather 对象 - - -def getMeetingDay(): +def getDaysUntil(date_str): + target_date = datetime.strptime(date_str, "%Y-%m-%d") tz = pytz.timezone("Asia/Shanghai") now = datetime.now(tz) - day = int((now.timestamp() - meetingTimestamp) / (24 * 60 * 60)) - print(day) - print("相遇的:", day) - return day - - -def getBirthDayOfLover(): - tz = pytz.timezone("Asia/Shanghai") - yearNow = datetime.now(tz) - dt = datetime(yearNow.year, yearNow.month, yearNow.day) - # 判断今年的生日是否已经过去 - birthday = datetime(yearNow.year, monthOfBirthday, dayOfBirthday) - if birthday.timestamp() < yearNow.timestamp(): - # 下一年的生日 - birthday = datetime(birthday.year + 1, monthOfBirthday, dayOfBirthday) - day = int((birthday.timestamp() - dt.timestamp()) / (24 * 60 * 60)) - print("生日:", day) - return day - - -def getExpressLoveDay(): - # unixTimeStamp = 1599148800 - tz = pytz.timezone("Asia/Shanghai") - now = datetime.now(tz) - day = int((now.timestamp() - expressLoveTimestamp) / (24 * 60 * 60)) - print(day) - print("相爱的天:", day) - return day - - -class DailyWord: - def __init__(self): - self.sid = "" - self.note = "" - self.content = "" - self.pic = "" - - def isValide(self) -> bool: - return self.sid != "" - - def getDailyWordHtml(self) -> str: - return '
每日一句
{}
{}
'.format( - self.content, self.note, self.pic - ) - - -def getDailyWord() -> DailyWord: - url = "http://open.iciba.com/dsapi" - r = requests.get(url) - r.encoding = "utf-8" - result = r.json() - dw = DailyWord() - if result.get("sid"): - dw.sid = result["sid"] - dw.note = result["note"] - dw.content = result["content"] - dw.pic = result["fenxiang_img"] - return dw - - -def sendDailyWordToWechatWork(dw: DailyWord): - if dw.isValide(): - webhook = ( - f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={qywxWebhookKey}" - ) - header = {"Content-Type": "application/json", "Charset": "UTF-8"} - message = { - "msgtype": "news", - "news": { - "articles": [ - { - "title": "每日一句", - "description": dw.content, - "url": dw.pic, - "picurl": dw.pic, - } - ] - }, - } - message_json = json.dumps(message) - requests.post(url=webhook, data=message_json, headers=header) - return - + return (target_date - now).days def sendAlarmMsg(mdTex): wechatwork(mdTex) - def wechatwork(tex): webhook = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={qywxWebhookKey}" header = {"Content-Type": "application/json", "Charset": "UTF-8"} message = {"msgtype": "markdown", "markdown": {"content": tex}} - print(f"wechat send msg, key:{qywxWebhookKey}") - print(message) message_json = json.dumps(message) try: requests.post(url=webhook, data=message_json, headers=header) @@ -237,14 +32,13 @@ def wechatwork(tex): print("send message to wechat server, err:", e2) sendAlarmMsg(str(e2)) - def wxPusher(tex): url = "http://wxpusher.zjiecode.com/api/send/message" header = {"Content-Type": "application/json", "Charset": "UTF-8"} message = { "appToken": wxpushAppToken, "content": tex, - "summary": "相爱一生", + "summary": "按时吃药提醒", "contentType": 2, "topicIds": wxpushTopicIds, "url": "http://wxpusher.zjiecode.com", @@ -260,64 +54,18 @@ def wxPusher(tex): print("send message to wx, err:", e) sendAlarmMsg(str(e)) - if __name__ == "__main__": - h = getMsgHeader() - w = getWeather() - bd = getBirthDayOfLover() - md = getMeetingDay() - ed = getExpressLoveDay() - dw = getDailyWord() - - # 企业微信 - w1 = w.getWeatherTextToWechatWork() - # tex1 = '{}\n> 今天是我们相爱的 {} 天\n我们已经相遇 {} - # 天({})\n距离你的生日还有 {} 天\n\n{}'.format( - # h, ed, md,datetime.utcfromtimestamp(meetingTimestamp).strftime('%Y-%m-%d %H:%M:%S') , bd, w1 - # ) - - # 一行代码完成转换和格式化,并插入到原始字符串中 - - tex1 = ( - '{}\n> 今天是我们相爱的 {} 天({})\n' - '我们已经相遇 {} 天({})\n' - '距离你的生日还有 {} 天' - ).format( - h, - ed, - datetime.fromtimestamp(expressLoveTimestamp, tz=pytz.utc) - .astimezone(pytz.timezone("Asia/Shanghai")) - .strftime("%Y-%m-%d"), - md, - datetime.fromtimestamp(meetingTimestamp, tz=pytz.utc) - .astimezone(pytz.timezone("Asia/Shanghai")) - .strftime("%Y-%m-%d"), - bd, + days_until_end = getDaysUntil("2024-10-27") + + # 新增的提醒内容 + medication_reminder = ( + '宝宝快要下班了呢,记得按时吃药哦:' + '饭前半小时:雷贝拉唑 * 1,枸酸秘钾 * 2;' + '饭后半小时:阿莫西林 * 4,克拉霉素 * 2。' ) - wechatwork(tex1) - sendDailyWordToWechatWork(dw) + # 发送提醒内容到企业微信 + wechatwork(medication_reminder) - # wxpusher - h2 = getMsgHeaderToWechat() - w2 = w.getWeatherTextToWechat() - dw2 = dw.getDailyWordHtml() - tex2 = ( - '{}
今天是我们相爱的 {} 天({})
' - '我们已经相遇{}天({})
' - '距离你的生日还有 {}

{}
{}' - ).format( - h2, - ed, - datetime.fromtimestamp(expressLoveTimestamp, tz=pytz.utc) - .astimezone(pytz.timezone("Asia/Shanghai")) - .strftime("%Y-%m-%d"), - md, - datetime.fromtimestamp(meetingTimestamp, tz=pytz.utc) - .astimezone(pytz.timezone("Asia/Shanghai")) - .strftime("%Y-%m-%d"), - bd, - w2, - dw2, - ) - wxPusher(tex2) + # 发送提醒内容到WxPusher + wxPusher(medication_reminder) From 2293e9104b6870832fe6a231019a431fc7cd7c1d Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 22:43:03 +0800 Subject: [PATCH 09/16] Update config.dev.yaml --- config.dev.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/config.dev.yaml b/config.dev.yaml index fcf15cf..f2b0b60 100644 --- a/config.dev.yaml +++ b/config.dev.yaml @@ -11,7 +11,7 @@ weather: city: 420100 # https://a.amap.com/lbs/static/code_resource/AMap_adcode_citycode.zip lover: - expressLoveTimestamp: 1136185445 - monthOfBirthday: 1 - dayOfBirthday: 1 - meetingTimestamp: 1136185445 + expressLoveTimestamp: 1594378800 + monthOfBirthday: 8 + dayOfBirthday: 19 + meetingTimestamp: 1504233600 From 2b40b59e3a9cddaea2b39ce14757d43843ba4dfd Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 22:57:14 +0800 Subject: [PATCH 10/16] Update config.dev.yaml --- config.dev.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config.dev.yaml b/config.dev.yaml index f2b0b60..b0016dc 100644 --- a/config.dev.yaml +++ b/config.dev.yaml @@ -7,8 +7,8 @@ wechatWork: webhookKey: "xxxxxx" # 企业微信的webhook key weather: - apiKey: "xxxxxxxxxxxxx" # 高德天气接口的key - city: 420100 # https://a.amap.com/lbs/static/code_resource/AMap_adcode_citycode.zip + apiKey: "fd14b9ca913160e65eb47b1edba5d48c" # 高德天气接口的key + city: 610118 # https://a.amap.com/lbs/static/code_resource/AMap_adcode_citycode.zip lover: expressLoveTimestamp: 1594378800 From d879fba770ef95951f15605b256d3cef1915a34b Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 23:03:06 +0800 Subject: [PATCH 11/16] Update send_morning_message.py From 7c1ba87fe9f9296ac4d279c4c82cc719cca4b5e1 Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 23:10:11 +0800 Subject: [PATCH 12/16] Update config.dev.yaml --- config.dev.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config.dev.yaml b/config.dev.yaml index b0016dc..c12ff3e 100644 --- a/config.dev.yaml +++ b/config.dev.yaml @@ -1,5 +1,5 @@ wxPusher: - appToken: "xxxxxxxxxxxxxxxxxxxxxx" # wxPusher的appToken + appToken: "AT_penx9gyzxwP6g7dwd4lb6LoWHskuGPiE" # wxPusher的appToken topicIds: - xxxx # wxPusher的topicIds,支持多个ID From cbcf22a8cab62129eaa65bdb77fea55f450b42bf Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 23:19:35 +0800 Subject: [PATCH 13/16] Update config.dev.yaml --- config.dev.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config.dev.yaml b/config.dev.yaml index c12ff3e..9b37656 100644 --- a/config.dev.yaml +++ b/config.dev.yaml @@ -1,7 +1,7 @@ wxPusher: appToken: "AT_penx9gyzxwP6g7dwd4lb6LoWHskuGPiE" # wxPusher的appToken topicIds: - - xxxx # wxPusher的topicIds,支持多个ID + - 34432 # wxPusher的topicIds,支持多个ID wechatWork: webhookKey: "xxxxxx" # 企业微信的webhook key From e109f303df7ff4acc7761ead3dbeef4f75d98f1b Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 23:21:49 +0800 Subject: [PATCH 14/16] Rename config.dev.yaml to config.yaml --- config.dev.yaml => config.yaml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename config.dev.yaml => config.yaml (100%) diff --git a/config.dev.yaml b/config.yaml similarity index 100% rename from config.dev.yaml rename to config.yaml From b64d3a1e59a443d59dfaee6d8900aea64da11731 Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 23:28:05 +0800 Subject: [PATCH 15/16] Update send_love.yml From ab54cf2f3a017ae886874b0deb0eafd52358b676 Mon Sep 17 00:00:00 2001 From: Bintong Zhao <74106084+BintongZhao@users.noreply.github.com> Date: Tue, 15 Oct 2024 23:32:12 +0800 Subject: [PATCH 16/16] Update send_love.yml