MihoyoBBSTools/push.py

258 lines
8.2 KiB
Python
Raw Normal View History

2022-01-09 09:31:44 +00:00
import os
2022-12-05 09:38:23 +00:00
import hmac
import time
2022-12-05 09:38:23 +00:00
import base64
2022-09-02 07:08:49 +00:00
import config
2022-12-05 09:38:23 +00:00
import urllib
import hashlib
2022-09-02 07:08:49 +00:00
from request import http
2022-12-05 09:38:23 +00:00
from loghelper import log
from configparser import ConfigParser, NoOptionError
2022-09-02 07:08:49 +00:00
2022-01-09 09:31:44 +00:00
cfg = ConfigParser()
def load_config():
2022-01-09 10:57:42 +00:00
config_path = os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config'), 'push.ini')
if os.path.exists(config_path):
cfg.read(config_path, encoding='utf-8')
return True
else:
return False
2022-01-09 09:31:44 +00:00
def title(status):
if status == 0:
return "「米游社脚本」执行成功!"
2022-04-25 08:07:37 +00:00
elif status == 1:
2022-01-09 09:31:44 +00:00
return "「米游社脚本」执行失败!"
2022-04-25 08:07:37 +00:00
elif status == 2:
return "「米游社脚本」部分账号执行失败!"
elif status == 3:
return "「米游社脚本」原神签到触发验证码!"
2022-01-09 09:31:44 +00:00
2022-04-20 05:00:29 +00:00
# telegram的推送
2022-08-23 15:43:09 +00:00
def telegram(send_title, push_message):
2022-01-25 07:03:53 +00:00
http.post(
url="https://{}/bot{}/sendMessage".format(cfg.get('telegram', 'api_url'), cfg.get('telegram', 'bot_token')),
data={
"chat_id": cfg.get('telegram', 'chat_id'),
2022-08-23 15:43:09 +00:00
"text": send_title + "\r\n" + push_message
2022-01-25 07:03:53 +00:00
}
)
2022-04-20 05:00:29 +00:00
# server酱
2022-08-23 15:43:09 +00:00
def ftqq(send_title, push_message):
2022-01-09 09:31:44 +00:00
http.post(
url="https://sctapi.ftqq.com/{}.send".format(cfg.get('setting', 'push_token')),
data={
2022-08-23 15:43:09 +00:00
"title": send_title,
2022-01-09 09:31:44 +00:00
"desp": push_message
}
)
2022-04-20 05:00:29 +00:00
# pushplus
2022-08-23 15:43:09 +00:00
def pushplus(send_title, push_message):
2022-01-09 09:31:44 +00:00
http.post(
2022-04-20 05:00:29 +00:00
url="https://www.pushplus.plus/send",
2022-01-09 09:31:44 +00:00
data={
"token": cfg.get('setting', 'push_token'),
2022-08-23 15:43:09 +00:00
"title": send_title,
2022-01-09 09:31:44 +00:00
"content": push_message
}
)
2022-04-20 05:00:29 +00:00
# cq http协议的推送
2022-08-23 15:43:09 +00:00
def cqhttp(send_title, push_message):
2022-01-09 09:31:44 +00:00
http.post(
url=cfg.get('cqhttp', 'cqhttp_url'),
json={
"user_id": cfg.getint('cqhttp', 'cqhttp_qq'),
2022-08-23 15:43:09 +00:00
"message": send_title + "\r\n" + push_message
2022-01-09 09:31:44 +00:00
}
)
2022-12-05 09:38:23 +00:00
# smtp mail(电子邮件)
# 感谢 @islandwind 提供的随机壁纸api 个人主页https://space.bilibili.com/7600422
2022-09-02 07:08:49 +00:00
def smtp(send_title, push_message):
import smtplib
from email.mime.text import MIMEText
2022-11-18 11:13:46 +00:00
2022-09-14 23:02:54 +00:00
IMAGE_API = "http://api.iw233.cn/api.php?sort=random&type=json"
2022-11-18 11:13:46 +00:00
try:
2022-09-14 23:02:54 +00:00
image_url = http.get(IMAGE_API).json()["pic"][0]
except:
image_url = "unable to get the image"
log.warning("获取随机背景图失败请检查图片api")
with open("assets/email_example.html", encoding="utf-8") as f:
2022-09-02 07:08:49 +00:00
EMAIL_TEMPLATE = f.read()
2022-09-14 23:02:54 +00:00
message = EMAIL_TEMPLATE.format(title=send_title, message=push_message.replace("\n", "<br/>"), image_url=image_url)
2022-09-02 07:08:49 +00:00
message = MIMEText(message, "html", "utf-8")
message['Subject'] = cfg["smtp"]["subject"]
message['To'] = cfg["smtp"]["toaddr"]
message['From'] = f"{cfg['smtp']['subject']}<{cfg['smtp']['fromaddr']}>"
2022-09-14 23:02:54 +00:00
if cfg.getboolean("smtp", "ssl_enable"):
server = smtplib.SMTP_SSL(cfg["smtp"]["mailhost"], cfg.getint("smtp", "port"))
else:
server = smtplib.SMTP(cfg["smtp"]["mailhost"], cfg.getint("smtp", "port"))
server.login(cfg["smtp"]["username"], cfg["smtp"]["password"])
server.sendmail(cfg["smtp"]["fromaddr"], cfg["smtp"]["toaddr"], message.as_string())
server.close()
2022-09-02 07:08:49 +00:00
log.info("邮件发送成功啦")
2022-01-09 09:31:44 +00:00
2022-04-20 05:00:29 +00:00
# 企业微信 感谢linjie5492@github
2022-08-23 15:43:09 +00:00
def wecom(send_title, push_message):
2022-04-20 05:00:29 +00:00
secret = cfg.get('wecom', 'secret')
corpid = cfg.get('wecom', 'wechat_id')
try:
touser = cfg.get('wecom', 'touser')
2022-12-05 09:38:23 +00:00
except NoOptionError:
# 没有配置时赋默认值
touser = '@all'
2022-11-18 11:13:46 +00:00
2022-04-20 05:00:29 +00:00
push_token = http.post(
url=f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}',
data=""
).json()['access_token']
2022-04-20 05:00:29 +00:00
push_data = {
"agentid": cfg.get('wecom', 'agentid'),
"msgtype": "text",
"touser": touser,
2022-04-20 05:00:29 +00:00
"text": {
2022-08-23 15:43:09 +00:00
"content": send_title + "\r\n" + push_message
},
"safe": 0
}
2022-04-20 05:00:29 +00:00
http.post(f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={push_token}', json=push_data)
2022-04-20 05:44:55 +00:00
# pushdeer
2022-08-23 15:43:09 +00:00
def pushdeer(send_title, push_message):
2022-04-20 05:44:55 +00:00
http.get(
url=f'{cfg.get("pushdeer", "api_url")}/message/push',
params={
2022-04-21 09:08:41 +00:00
"pushkey": cfg.get("pushdeer", "token"),
2022-08-23 15:43:09 +00:00
"text": send_title,
2022-04-20 05:44:55 +00:00
"desp": str(push_message).replace("\r\n", "\r\n\r\n"),
"type": "markdown"
}
)
# 钉钉群机器人
2022-08-23 15:43:09 +00:00
def dingrobot(send_title, push_message):
api_url = cfg.get('dingrobot', 'webhook') # https://oapi.dingtalk.com/robot/send?access_token=XXX
secret = cfg.get('dingrobot', 'secret') # 安全设置 -> 加签 -> 密钥 -> SEC*
if secret:
timestamp = str(round(time.time() * 1000))
sign_string = f"{timestamp}\n{secret}"
hmac_code = hmac.new(
key=secret.encode("utf-8"),
msg=sign_string.encode("utf-8"),
digestmod=hashlib.sha256
).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
api_url = f"{api_url}&timestamp={timestamp}&sign={sign}"
2022-11-18 11:13:46 +00:00
rep = http.post(
url=api_url,
headers={"Content-Type": "application/json; charset=utf-8"},
json={
2022-08-23 15:43:09 +00:00
"msgtype": "text", "text": {"content": send_title + "\r\n" + push_message}
}
).json()
log.info(f"推送结果:{rep.get('errmsg')}")
2022-12-05 09:38:23 +00:00
2022-10-13 05:19:10 +00:00
# 飞书机器人
def feishubot(send_title, push_message):
api_url = cfg.get('feishubot', 'webhook') # https://open.feishu.cn/open-apis/bot/v2/hook/XXX
rep = http.post(
url=api_url,
headers={"Content-Type": "application/json; charset=utf-8"},
json={
"msg_type": "text", "content": {"text": send_title + "\r\n" + push_message}
}
).json()
log.info(f"推送结果:{rep.get('msg')}")
2022-12-05 09:38:23 +00:00
2022-05-09 01:07:50 +00:00
# Bark
2022-08-23 15:43:09 +00:00
def bark(send_title, push_message):
2022-05-09 06:33:59 +00:00
rep = http.get(
2022-12-05 09:38:23 +00:00
url=f'{cfg.get("bark", "api_url")}/{cfg.get("bark", "token")}/{send_title}/{push_message}?icon=https://cdn'
f'.jsdelivr.net/gh/tanmx/pic@main/mihoyo/{cfg.get("bark", "icon")}.png'
2022-05-09 06:33:59 +00:00
).json()
log.info(f"推送结果:{rep.get('message')}")
2022-05-09 01:07:50 +00:00
2022-08-15 12:12:08 +00:00
# gotify
2022-08-23 15:43:09 +00:00
def gotify(send_title, push_message):
2022-08-15 12:12:08 +00:00
rep = http.post(
url=f'{cfg.get("gotify", "api_url")}/message?token={cfg.get("gotify", "token")}',
headers={"Content-Type": "application/json; charset=utf-8"},
json={
2022-08-23 15:43:09 +00:00
"title": send_title,
2022-08-20 01:49:22 +00:00
"message": push_message,
"priority": cfg.getint("gotify", "priority")
2022-08-15 12:12:08 +00:00
}
).json()
log.info(f"推送结果:{rep.get('errmsg')}")
2022-11-18 11:13:46 +00:00
# ifttt
def ifttt(send_title, push_message):
ifttt_event = cfg.get('ifttt', 'event')
ifttt_key = cfg.get('ifttt', 'key')
rep = http.post(
url=f'https://maker.ifttt.com/trigger/{ifttt_event}/with/key/{ifttt_key}',
headers={"Content-Type": "application/json; charset=utf-8"},
json={
"value1": send_title,
"value2": push_message
}
)
if 'errors' in rep.text:
log.warning(f"推送执行错误:{rep.json()['errors']}")
return 0
else:
log.info("推送完毕......")
return 1
2022-01-09 09:31:44 +00:00
def push(status, push_message):
2022-01-09 10:57:42 +00:00
if not load_config():
return 0
2022-01-09 09:31:44 +00:00
if cfg.getboolean('setting', 'enable'):
2022-01-11 07:54:47 +00:00
log.info("正在执行推送......")
func_name = cfg.get('setting', 'push_server').lower()
func = globals().get(func_name)
# print(func)
if not func:
log.warning("推送服务名称错误请检查config/push.ini -> [setting] -> push_server")
return 0
log.debug(f"推送所用的服务为:{func_name}")
2022-04-20 05:00:29 +00:00
try:
2022-08-28 10:27:48 +00:00
if not config.update_config_need:
2022-08-23 15:43:09 +00:00
func(title(status), push_message)
else:
func('「米游社脚本」config可能需要手动更新',
2022-12-05 09:38:23 +00:00
f'如果您多次收到此消息开头的推送证明您运行的环境无法自动更新config请手动更新一下谢谢\r\n{title(status)}\r\n{push_message}')
except Exception as r:
log.warning(f"推送执行错误:{str(r)}")
return 0
2022-04-20 05:00:29 +00:00
else:
log.info("推送完毕......")
return 1
if __name__ == "__main__":
push(0, f'推送验证{int(time.time())}')