QChatGPT/pkg/utils/announcement.py

69 lines
1.8 KiB
Python
Raw Normal View History

2023-03-15 15:43:36 +08:00
import base64
import os
2023-04-15 16:45:26 +08:00
import json
2023-03-15 15:43:36 +08:00
import requests
2023-04-15 16:45:26 +08:00
def read_latest() -> list:
import pkg.utils.network as network
2023-03-15 15:43:36 +08:00
resp = requests.get(
2023-04-15 16:45:26 +08:00
url="https://api.github.com/repos/RockChinQ/QChatGPT/contents/res/announcement.json",
proxies=network.wrapper_proxies()
2023-03-15 15:43:36 +08:00
)
obj_json = resp.json()
b64_content = obj_json["content"]
# 解码
content = base64.b64decode(b64_content).decode("utf-8")
2023-04-15 16:45:26 +08:00
return json.loads(content)
2023-03-15 15:43:36 +08:00
2023-04-15 16:45:26 +08:00
def read_saved() -> list:
2023-03-15 15:43:36 +08:00
# 已保存的在res/announcement_saved
# 检查是否存在
2023-04-15 16:45:26 +08:00
if not os.path.exists("res/announcement_saved.json"):
with open("res/announcement_saved.json", "w", encoding="utf-8") as f:
f.write("[]")
2023-03-15 15:43:36 +08:00
2023-04-15 16:45:26 +08:00
with open("res/announcement_saved.json", "r", encoding="utf-8") as f:
2023-03-15 15:43:36 +08:00
content = f.read()
2023-04-15 16:45:26 +08:00
return json.loads(content)
2023-03-15 15:43:36 +08:00
2023-04-15 16:45:26 +08:00
def write_saved(content: list):
2023-03-15 15:43:36 +08:00
# 已保存的在res/announcement_saved
2023-04-15 16:54:50 +08:00
with open("res/announcement_saved.json", "w", encoding="utf-8") as f:
2023-04-15 16:45:26 +08:00
f.write(json.dumps(content, indent=4, ensure_ascii=False))
2023-03-15 15:43:36 +08:00
2023-04-15 16:45:26 +08:00
def fetch_new() -> list:
2023-03-15 15:43:36 +08:00
latest = read_latest()
saved = read_saved()
2023-04-15 16:45:26 +08:00
to_show: list = []
for item in latest:
# 遍历saved检查是否有相同id的公告
for saved_item in saved:
if saved_item["id"] == item["id"]:
break
else:
# 没有相同id的公告
to_show.append(item)
write_saved(latest)
return to_show
if __name__ == '__main__':
resp = requests.get(
url="https://api.github.com/repos/RockChinQ/QChatGPT/contents/res/announcement.json",
)
obj_json = resp.json()
b64_content = obj_json["content"]
# 解码
content = base64.b64decode(b64_content).decode("utf-8")
print(json.dumps(json.loads(content), indent=4, ensure_ascii=False))