Skip to content

Commit

Permalink
Update
Browse files Browse the repository at this point in the history
- 新增企业微信推送通道
- 新增输出缓存
  • Loading branch information
lywly committed May 7, 2022
1 parent b83ace9 commit a0cfbb1
Show file tree
Hide file tree
Showing 15 changed files with 260 additions and 108 deletions.
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@

*.pyc
*.html

/.idea/*
/.git/*
/__pycache__/*
/Mail_Push_Core/__pycache__/*
/dist/*
17 changes: 11 additions & 6 deletions BIT_Mail.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
from apscheduler.triggers.cron import CronTrigger
import warnings

from Mail_Push_Core.keywds_cache import kc_delete
from Mail_Push_Core.keywds_cache import cache_delete
from Mail_Push_Core.myprint import myprint

warnings.filterwarnings("ignore")

from Mail_Push_Core.Wechat_push import push_config
from Mail_Push_Core.Pushing import push_config
from Mail_Push_Core.file_select_GUI import file_select_GUI
from Mail_Push_Core.monitor_config import monitor_config
from Mail_Push_Core.mail_keywds import keywds_monitor
Expand Down Expand Up @@ -36,10 +37,10 @@ def main():
BIT_mail = imaplib.IMAP4(host=Imap_url, port=Port)
try:
BIT_mail.login(User, Passwd)
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 验证成功,账户密码正确,定时任务已启动')
myprint(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 验证成功,登录信息正确,定时任务已启动')
except Exception as e:
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 验证失败,请重新检查登录信息')
print("ErrorType : {}, Error : {}".format(type(e).__name__, e))
myprint(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' 验证失败,请重新检查登录信息')
myprint("ErrorType : {}, Error : {}".format(type(e).__name__, e))
BIT_mail.logout()

scheduler = BlockingScheduler(timezone="Asia/Shanghai")
Expand All @@ -50,14 +51,18 @@ def main():
scheduler.add_job(keywds_monitor, trigger_Keywords, max_instances=5,
args=[Imap_url, Port, User, Passwd, Date_range, Keywords_raw, Sendkeys])
trigger_kc_delete = CronTrigger(hour='02', minute='03') # 缓存清理时间,每天凌晨2点
scheduler.add_job(kc_delete, trigger_kc_delete, max_instances=5)
scheduler.add_job(cache_delete, trigger_kc_delete, max_instances=5)
# 添加邮件汇总推送任务
trigger_mail_summary = CronTrigger(hour=hour_summary, minute=minute_summary, second='30')
scheduler.add_job(mail_summary, trigger_mail_summary, max_instances=5,
args=[Imap_url, Port, User, Passwd, Date_range, Sendkeys])
# 启动任务
scheduler.start()

# 调试使用
# keywds_monitor(Imap_url, Port, User, Passwd, Date_range, Keywords_raw, Sendkeys)
# mail_summary(Imap_url, Port, User, Passwd, Date_range, Sendkeys)


if __name__ == '__main__':
main()
76 changes: 76 additions & 0 deletions Mail_Push_Core/Pushing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import requests
import json
import configparser

from Mail_Push_Core.Wechat import WeChat
from Mail_Push_Core.myprint import myprint
# 打包exe
import os
import sys

os.environ['REQUESTS_CA_BUNDLE'] = os.path.join(os.path.dirname(sys.argv[0]), 'cacert.pem')


def push_config(config_filename):
config_data = configparser.ConfigParser()
config_data.read(config_filename, encoding='utf-8')

my_push_url = config_data.get('Sendkey', 'my_push_url')
push_plus_sendkey = config_data.get('Sendkey', 'push_plus_sendkey')
CORPID = config_data.get('Sendkey', 'QYWX_CORPID')
CORPSECRET = config_data.get('Sendkey', 'QYWX_CORPSECRET')
agentid = config_data.get('Sendkey', 'QYWX_agentid')

return [my_push_url, push_plus_sendkey, [CORPID, CORPSECRET, agentid]]


def push(Pushing_Data, Sendkeys):
# 自建通道
if Sendkeys[0] != '':
# 将url改为自建地址
my_Pushing_Data = Pushing_Data.replace("\n", "%0D%0A")
my_url = Sendkeys[0] + my_Pushing_Data
my_send_info = requests.get(my_url)
if "\"errmsg\":\"ok\"" in str(my_send_info.content, encoding="utf-8"):
myprint('自建通道已推送')
else:
myprint('自建通道推送超时')
else:
pass
# myprint('未配置自建通道推送')

# PushPlus通道"msg":"请求成功"
if Sendkeys[1] != '':
pushplus_token = Sendkeys[1]
pushplus_title = '北理工邮箱推送'
pushplus_template = 'html'
pushplus_url = 'http://www.pushplus.plus/send'
pushplus_data = {
"token": pushplus_token,
"title": pushplus_title,
"content": Pushing_Data,
"template": pushplus_template
}
pushplus_body = json.dumps(pushplus_data).encode(encoding='utf-8')
pushplus_headers = {'Content-Type': 'application/json'}
pushplus_send_info = requests.post(pushplus_url, data=pushplus_body, headers=pushplus_headers)

if "\"msg\":\"请求成功\"" in str(pushplus_send_info.content, encoding="utf-8"):
myprint('PushPlus通道已推送')
else:
myprint('PushPlus通道推送超时')
else:
pass

if Sendkeys[2][0] != '':
qywx = WeChat()
qywx.CORPID = Sendkeys[2][0]
qywx.CORPSECRET = Sendkeys[2][1]
qywx.agentid = Sendkeys[2][2]
qywx_send_info = qywx.send_text(Pushing_Data)
if qywx_send_info:
myprint('企业微信通道已推送')
else:
myprint('企业微信通道推送超时')
else:
pass
64 changes: 64 additions & 0 deletions Mail_Push_Core/Wechat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import os
import time
import requests
import json


class WeChat:
def __init__(self):
self.CORPID = "" # 企业ID,在管理后台获取
self.CORPSECRET = "" # 自建应用的Secret,每个自建应用里都有单独的secret
self.agentid = ""
self.touser = "@all"

def _get_access_token(self): # 获取access_token
url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
values = {'corpid': self.CORPID, # 企业ID,
'corpsecret': self.CORPSECRET, # 应用的Secret
}
req = requests.post(url, params=values)
data = json.loads(req.text)
return data["access_token"], data["expires_in"]

def get_access_token(self):
cur_time = time.time() # 获取现在的时间
if not os.path.isdir('./cache'):
os.makedirs('./cache')
try:
with open('./cache/access_token.conf', 'r') as f:
t, expires_in, access_token = f.read().split() # 读取文件中的t即上次获取access token的时间和access token的值
if 0 < cur_time - float(t) < float(expires_in): # 判断access token是否在有效期内
return access_token # 如果在,则返回读取的access token
else: # 否则,先打开文件,权限可以编辑
with open('./cache/access_token.conf', 'w') as f:
access_token, expires_in = self._get_access_token() # 获取access token
f.write('\t'.join([str(cur_time), str(expires_in), access_token])) # 把获取到的Access token和当前时间写入文件
return access_token # 返回access token的值

except: # 如果是第一次运行,则运行此语句,获取access token的值
with open('./cache/access_token.conf', 'w') as f:
access_token, expires_in = self._get_access_token()
cur_time = time.time()
f.write('\t'.join([str(cur_time), str(expires_in), access_token]))
return access_token

def send_text(self, _message):
access_token = self.get_access_token()
json_dict = {
"touser": self.touser,
"msgtype": "text",
"agentid": self.agentid,
"text": {
"content": _message
},
"safe": 0,
"enable_id_trans": 1,
"enable_duplicate_check": 0,
"duplicate_check_interval": 1800
}
json_str = json.dumps(json_dict)
response_send = requests.post(
"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}".format(
access_token=access_token), data=json_str)
# print("send to " + useridstr + ' ' + json.loads(response_send.text)['errmsg'])
return json.loads(response_send.text)['errmsg'] == 'ok'
44 changes: 0 additions & 44 deletions Mail_Push_Core/Wechat_push.py

This file was deleted.

Binary file modified Mail_Push_Core/__pycache__/keywds_cache.cpython-39.pyc
Binary file not shown.
Binary file modified Mail_Push_Core/__pycache__/mail_keywds.cpython-39.pyc
Binary file not shown.
Binary file modified Mail_Push_Core/__pycache__/mail_login.cpython-39.pyc
Binary file not shown.
Binary file modified Mail_Push_Core/__pycache__/mail_summary.cpython-39.pyc
Binary file not shown.
26 changes: 16 additions & 10 deletions Mail_Push_Core/keywds_cache.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import os

from Mail_Push_Core.myprint import myprint


def kc_save(data):
with open('cache.txt', 'w') as f:
if not os.path.isdir('./cache'):
os.makedirs('./cache')
with open('./cache/cache.txt', 'w') as f:
for value in data:
f.write(str(value))
f.write('\n')
Expand All @@ -11,7 +15,9 @@ def kc_save(data):
def kc_load():
new_data = []
try:
with open('cache.txt', 'r') as f:
if not os.path.isdir('./cache'):
os.makedirs('./cache')
with open('./cache/cache.txt', 'r') as f:
data = list(f)
for value in data:
new_value = value.replace('\n', '')
Expand All @@ -21,14 +27,14 @@ def kc_load():
return new_data


def kc_delete():
def cache_delete():
try:
os.remove('cache.txt')
print(' ---------------------------------')
print(' | |')
print(' | 关键词缓存已清理 |')
print(' | 关键词缓存已清理 |')
print(' | |')
print(' ---------------------------------')
os.remove('./cache/cache.txt')
os.remove('./cache/print_cache.txt')
myprint(' ---------------------------------')
myprint(' | |')
myprint(' | 关键词缓存与打印缓存已清理 |')
myprint(' | |')
myprint(' ---------------------------------')
except:
pass
Loading

0 comments on commit a0cfbb1

Please sign in to comment.