Add more notify methods

This commit is contained in:
LuckyHunter
2022-10-21 02:15:50 +08:00
parent 7a098b0621
commit 0dc721b596
9 changed files with 175 additions and 74 deletions

3
.gitignore vendored
View File

@@ -129,4 +129,5 @@ dmypy.json
.pyre/ .pyre/
# cookies # cookies
cookies.json cookies.json
config.toml

View File

@@ -11,9 +11,13 @@
- `什么值得买`每日签到 - `什么值得买`每日签到
- 通过`pushplus`推送运行结果到微信 - 通过`pushplus`推送运行结果到微信
- 通过`server酱`推送运行结果到微信
- 通过`telegram bot`推送
## 2. 使用方法 ## 2. 使用方法
### 2.1 Git action 运行
1. Fork[此仓库项目](https://github.com/Chasing66/smzdm_bot)>点击右上角 Fork 按钮即可, 欢迎点`star`~ 1. Fork[此仓库项目](https://github.com/Chasing66/smzdm_bot)>点击右上角 Fork 按钮即可, 欢迎点`star`~
2. 修改 `.github/workflows/run.yml`里的下面部分, 取消注释,修改为你自己的时间 2. 修改 `.github/workflows/run.yml`里的下面部分, 取消注释,修改为你自己的时间
@@ -29,12 +33,20 @@ on:
3. Secret 新增`SMZDM_COOKIE`, 填入[什么值得买官网](https://www.smzdm.com/)获取的 Cookie 信息, [详见](#31-cookie获取方法) 3. Secret 新增`SMZDM_COOKIE`, 填入[什么值得买官网](https://www.smzdm.com/)获取的 Cookie 信息, [详见](#31-cookie获取方法)
4. (可选) Secret 新增`PUSH_PLUS_TOKEN`用于推送通知, [详见](https://www.pushplus.plus/) 4. (可选) Secret 新增`PUSH_PLUS_TOKEN`用于推送通知, [详见](https://www.pushplus.plus/)
5. 也可以在本地运行,通过设置环境变量 5. (可选) Secret 新增`SC_KEY`用于推送通知, [详见](https://sct.ftqq.com/)
6. (可选) Secret 新增`TG_BOT_TOKEN``TG_USER_ID`用于推送通知
### 2.2 本地运行
1. 配置`config.toml`运行, 生成`config/config_example.toml`并按照需求配置
```bash
export SMZDM_COOKIE=xxxx
export PUSH_PLUS_TOKEN=xxxx
``` ```
cp config/config_example.toml config/config.toml
```
### 2.2 使用 Cookie Editor
也可以使用浏览器扩展 [Cookie Editor](https://microsoftedge.microsoft.com/addons/detail/cookie-editor/oaaopmblghnnjfgbgmflnkjkilhihdpb)导出 cookies, 另存为`cookies.json`在项目的根目录
## 3. 其它 ## 3. 其它
@@ -43,7 +55,3 @@ export PUSH_PLUS_TOKEN=xxxx
- 使用 Chrome 浏览器访问[什么值得买官网](https://www.smzdm.com/), 登录账号 - 使用 Chrome 浏览器访问[什么值得买官网](https://www.smzdm.com/), 登录账号
- 打开开发者工具 (Windows 快捷键`F12`, MacOS 快捷键`option + command + i`) - 打开开发者工具 (Windows 快捷键`F12`, MacOS 快捷键`option + command + i`)
- 选择 Network, 刷新页面, 选择第一个`www.smzdm.com`, 找到`Requests Headers`里的`Cookie` - 选择 Network, 刷新页面, 选择第一个`www.smzdm.com`, 找到`Requests Headers`里的`Cookie`
#### 3.1.1 使用 Cookie Editor
也可以使用浏览器扩展 [Cookie Editor](https://microsoftedge.microsoft.com/addons/detail/cookie-editor/oaaopmblghnnjfgbgmflnkjkilhihdpb)导出 cookies, 另存为`cookies.json`在项目的根目录

View File

@@ -0,0 +1,8 @@
# Cookie
SMZDM_COOKIE = ''
# Notification
PUSH_PLUS_TOKEN = ''
SC_KEY = ''
TG_BOT_TOKEN = ''
TG_USER_ID = ''

69
main.py
View File

@@ -1,10 +1,17 @@
import json import json
import os import os
import sys import sys
from pprint import pprint from pathlib import Path
from pprint import pp, pprint
import prettytable as pt
import requests import requests
from notifications.pushplus import pushplus
from notify.notify import NotifyBot
from utils.file_helper import TomlHelper
CURRENT_PATH = Path(__file__).parent.resolve()
CONFIG_PATH = Path(CURRENT_PATH, 'config')
class SMZDM_Bot(object): class SMZDM_Bot(object):
@@ -21,7 +28,7 @@ class SMZDM_Bot(object):
'Sec-Fetch-Site': 'same-site', 'Sec-Fetch-Site': 'same-site',
'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' 'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) ' 'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/74.0.3729.131 Safari/537.36'), 'Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.42'),
} }
def __init__(self): def __init__(self):
@@ -40,11 +47,17 @@ class SMZDM_Bot(object):
if resp.status_code == 200: if resp.status_code == 200:
resp_data = resp.json()["data"] resp_data = resp.json()["data"]
checkin_num = resp_data["checkin_num"] checkin_num = resp_data["checkin_num"]
days_of_week = resp_data["continue_checkin_days"]
gold = resp_data["gold"] gold = resp_data["gold"]
point = resp_data["point"] point = resp_data["point"]
exp = resp_data["exp"] exp = resp_data["exp"]
rank = resp_data["rank"] rank = resp_data["rank"]
cards = resp_data["cards"] cards = resp_data["cards"]
tb = pt.PrettyTable()
tb.field_names = ["签到天数", "星期", "金币", "积分", "经验", "等级", "补签卡"]
tb.add_row([checkin_num, days_of_week,
gold, point, exp, rank, cards])
pprint(tb)
msg = f'''⭐签到成功{checkin_num} msg = f'''⭐签到成功{checkin_num}
🏅金币{gold} 🏅金币{gold}
🏅积分{point} 🏅积分{point}
@@ -54,30 +67,40 @@ class SMZDM_Bot(object):
return msg return msg
else: else:
pprint("Faile to sign in") pprint("Faile to sign in")
if __name__ == '__main__':
smzdm_bot = SMZDM_Bot()
if not os.environ.get("SMZDM_COOKIE", None):
current_dir = os.path.dirname(os.path.realpath(__file__))
cookies_file_path = os.path.join(current_dir, 'cookies.json')
if not os.path.exists(cookies_file_path):
pprint("Cookies not existed, exit")
sys.exit(1) sys.exit(1)
with open("cookies.json", "r") as f:
def main():
smzdm_bot = SMZDM_Bot()
conf_kwargs = {}
if Path.exists(Path(CONFIG_PATH, "config.toml")):
pprint("Get configration from config.toml")
conf_kwargs = TomlHelper(Path(CONFIG_PATH, "config.toml")).read()
elif os.environ.get("SMZDM_COOKIE", None):
pprint("Get configration from env")
conf_kwargs = {
"SMZDM_COOKIE": os.environ.get("SMZDM_COOKIE"),
"PUSH_PLUS_TOKEN": os.environ.get("PUSH_PLUS_TOKEN", None),
"SC_KEY": os.environ.get("SC_KEY", None),
"TG_BOT_TOKEN": os.environ.get("TG_BOT_TOKEN", None),
"TG_USER_ID": os.environ.get("TG_USER_ID", None),
}
elif Path.exists(Path(CONFIG_PATH, "cookies.json")):
pprint("Load cookis from cookies.json")
with open(Path(CONFIG_PATH, "cookies.json", "r")) as f:
cookies = json.load(f) cookies = json.load(f)
smzdm_cookies = {} smzdm_cookies = {}
for cookie in cookies: for cookie in cookies:
smzdm_cookies.update({cookie["name"]: cookie["value"]}) smzdm_cookies.update({cookie["name"]: cookie["value"]})
smzdm_bot.update_cookies(smzdm_cookies) smzdm_bot.update_cookies(smzdm_cookies)
else: if conf_kwargs.get("SMZDM_COOKIE", None):
smzdm_cookies = os.environ.get( SMZDM_COOKIE = conf_kwargs.get(
"SMZDM_COOKIE").encode('UTF-8').decode('latin-1') "SMZDM_COOKIE").encode('UTF-8').decode('latin-1')
smzdm_bot.set_cookies(smzdm_cookies) smzdm_bot.set_cookies(SMZDM_COOKIE)
resp = smzdm_bot.checkin() msg = smzdm_bot.checkin()
if not os.environ.get('PUSH_PLUS_TOKEN'): NotifyBot(content=msg, **conf_kwargs)
pprint("Skip PushPlus notication")
else:
title = '什么值得买每日签到' if __name__ == '__main__':
token = os.environ.get('PUSH_PLUS_TOKEN') main()
pushplus(title=title, content=resp, token=token)

View File

@@ -1,25 +0,0 @@
import json
import requests
import os
def pushplus(title, content, token, template='html'):
url = 'https://www.pushplus.plus/send'
body = {
'token': token,
'title': title,
'content': content,
'template': template
}
data = json.dumps(body).encode(encoding='utf-8')
headers = {'Content-Type': 'application/json'}
rsp = requests.post(url, data=data, headers=headers)
return rsp.json()
if __name__ == '__main__':
token = os.environ.get('PUSH_PLUS_TOKEN')
res = pushplus(title='Title',
content='Content',
token=token)
print(res)

View File

@@ -1,17 +0,0 @@
import requests
import os
def serverchan(text, desp, secretKey):
url = f'http://sc.ftqq.com/{secretKey}.send'
session = requests.Session()
data = {'text': text, 'desp': desp}
resp = session.post(url, data=data)
return resp.json()
if __name__ == '__main__':
token = os.environ.get('PUSH_PLUS_TOKEN')
resp = serverchan(text='test', desp='hi',
secretKey=token)
print(resp)

72
notify/notify.py Normal file
View File

@@ -0,0 +1,72 @@
import json
import os
from pprint import pp, pprint
from typing import Dict
import requests
class NotifyBot(object):
def __init__(self, content, title="什么值得买签到", **kwargs: Dict) -> None:
self.content = content
self.title = title
self.kwargs = kwargs
self.push_plus()
self.server_chain()
self.tg_bot()
def push_plus(self, template='html'):
if self.kwargs.get("PUSH_PLUS_TOKEN", None):
PUSH_PLUS_TOKEN = self.kwargs.get("PUSH_PLUS_TOKEN")
else:
pprint("⚠️ PUSH_PLUS_TOKEN not set, skip PushPlus nofitication")
return
url = 'https://www.pushplus.plus/send'
body = {
'token': PUSH_PLUS_TOKEN,
'title': self.title,
'content': self.content,
'template': template
}
data = json.dumps(body).encode(encoding='utf-8')
headers = {'Content-Type': 'application/json'}
resp = requests.post(url, data=data, headers=headers)
if resp.status_code == 200:
pprint("✅ Push Plus notified")
return resp.json()
def server_chain(self):
if self.kwargs.get("SC_KEY", None):
SC_KEY = self.kwargs.get("SC_KEY")
else:
pprint("⚠️ SC_KEY not set, skip ServerChain notification")
return
url = f'http://sc.ftqq.com/{SC_KEY}.send'
data = {'text': self.title, 'desp': self.content}
resp = requests.post(url, data=data)
if resp.status_code == 200:
pprint("✅ Server Chain notified")
return resp.json()
def tg_bot(self):
if self.kwargs.get("TG_BOT_TOKEN", None) and self.kwargs.get("TG_USER_ID", None):
TG_BOT_TOKEN = self.kwargs.get("TG_BOT_TOKEN")
TG_USER_ID = self.kwargs.get("TG_USER_ID")
else:
pprint("⚠️ TG_BOT_TOKEN & TG_USER_ID not set, skip TelegramBot notification")
return
url = f"https://api.telegram.org/bot{TG_BOT_TOKEN}/sendMessage"
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'chat_id': str(TG_USER_ID),
'text': f'{self.title}\n\n{self.content}',
'disable_web_page_preview': 'true'}
resp = requests.post(url=url, headers=headers, params=payload)
if resp.status_code == 200:
pprint("✅ Telegram Bot notified")
return resp.json()

View File

@@ -2,6 +2,9 @@ certifi==2022.9.24
charset-normalizer==2.1.1 charset-normalizer==2.1.1
docopt==0.6.2 docopt==0.6.2
idna==3.4 idna==3.4
prettytable==3.4.1
requests==2.28.1 requests==2.28.1
toml==0.10.2
urllib3==1.26.12 urllib3==1.26.12
wcwidth==0.2.5
yarg==0.1.9 yarg==0.1.9

28
utils/file_helper.py Normal file
View File

@@ -0,0 +1,28 @@
import toml
class TomlHelper:
def __init__(self, toml_filename):
self.t_dict = dict()
self.toml_file_path = toml_filename
def update(self, t_data):
self.t_dict.update(t_data)
return self.t_dict
def write(self, t_data):
with open(self.toml_file_path, "w", encoding="utf-8") as fs:
toml.dump(t_data, fs)
def read(self):
with open(self.toml_file_path, "r", encoding="utf-8") as fs:
t_data = toml.load(fs)
return t_data
def read_str(self, s_data):
t_data = toml.loads(s_data, _dict=dict)
return t_data
def read_dict(self, dict):
t_data = toml.dumps(dict)
return t_data