forked from hustuhao/FunnyCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsend_morning_message.py
More file actions
357 lines (308 loc) · 11.2 KB
/
send_morning_message.py
File metadata and controls
357 lines (308 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
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 = '今天是 <font color="info">{}</font>'.format(dt.strftime("%Y-%m-%d %A"))
return h
def getMsgHeaderToWechat():
tz = pytz.timezone("Asia/Shanghai")
dt = datetime.now(tz)
h = '今天是 <font color="#87CEEB">{}</font>'.format(dt.strftime("%Y-%m-%d %A"))
return h
from datetime import datetime
def getDaysUntil(target_date):
target_date = datetime.strptime(target_date, "%Y-%m-%d")
today = datetime.today()
delta = target_date - today
return delta.days
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 > <font color="info">{}</font>, 白天温度: <font color="info">{}</font> ~ 晚上温度: <font color="info">{}</font>\n白天风力:{}-{},晚上风力:{}-{}。'.format(
self.dayweather,
self.daytemp,
self.nighttemp,
self.daypower,
self.daywind,
self.nightpower,
self.nightwind,
)
return tex
def getWeatherTextToWechat(self):
tex = '<hr>西安天气 <br> <font color="green">{}</font>, 白天温度: <font color="green">{}</font> ~ 晚上温度: <font color="green">{}</font>, 白天风力:{}-{},晚上风力:{}-{}。'.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 '<br>每日一句<br>{}<br>{}<br><img src="{}" align="center">'.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))
def wxPusher2(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()
days_until_end = getDaysUntil("2024-10-27")
# 新增的提醒内容
medication_reminder = (
'宝宝记得按时吃药哦,再坚持<font color="warning"> {} </font>天就好啦:<br>'
'早晨空腹:雷贝拉唑 * 1,枸酸秘钾 * 2;<br>'
'饭后半小时:阿莫西林 * 4,克拉霉素 * 2。').format(days_until_end)
# 企业微信
w1 = w.getWeatherTextToWechatWork()
# tex1 = '{}\n> 今天是我们相爱的<font color="warning"> {} </font>天\n我们已经相遇<font color="warning"> {}
# </font>天({})\n距离你的生日还有<font color="warning"> {} </font>天\n\n{}'.format(
# h, ed, md,datetime.utcfromtimestamp(meetingTimestamp).strftime('%Y-%m-%d %H:%M:%S') , bd, w1
# )
# 一行代码完成转换和格式化,并插入到原始字符串中
tex1 = (
'{}\n> 今天是我们相爱的<font color="warning"> {} </font>天({})<br>'
'我们已经相遇<font color="warning"> {} </font>天({})<br>'
'距离你的生日还有<font color="warning"> {} </font>天'
).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 = (
'{}<br> 今天是我们相爱的<font color="green"> {} </font>天({})<br>'
'我们已经相遇<font color="green">{}</font>天({})<br>'
'距离你的生日还有<font color="green"> {} </font>天<br><br>{}<br>{}'
).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)
#wxPusher2(medication_reminder)