Skip to content

Commit

Permalink
Merge pull request IlineI#27 from chase535/main
Browse files Browse the repository at this point in the history
优化代码,添加一个小程序判定
  • Loading branch information
IlineI authored Sep 24, 2022
2 parents 48a8694 + 6869073 commit ec3e97a
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 69 deletions.
2 changes: 1 addition & 1 deletion WeChatPush/itchat/async_components/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def produce_msg(core, msgList):
elif m.get('AppMsgType') == 17:
msg['Type'] = 'Locationshare'
msg['Text'] = m.get('FileName')
elif m.get('AppMsgType') == 33:
elif m.get('AppMsgType') in (33, 36):
msg['Type'] = 'Miniprogram'
msg['Text'] = m.get('FileName')
elif m.get('AppMsgType') == 2000:
Expand Down
2 changes: 1 addition & 1 deletion WeChatPush/itchat/components/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def produce_msg(core, msgList):
elif m.get('AppMsgType') == 17:
msg['Type'] = 'Locationshare'
msg['Text'] = m.get('FileName')
elif m.get('AppMsgType') == 33:
elif m.get('AppMsgType') in (33, 36):
msg['Type'] = 'Miniprogram'
msg['Text'] = m.get('FileName')
elif m.get('AppMsgType') == 2000:
Expand Down
143 changes: 76 additions & 67 deletions WeChatPush/main.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
# coding=utf-8

import os

pid = os.getpid()
ppid = os.getppid()

import sys
import signal
from datetime import datetime


def prt(mes):
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + str(mes))


if int(sys.version_info.major) < 3:
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '程序仅支持Python3.4及以上版本运行,程序强制停止运行')
os.kill(pid, signal.SIGTERM)
prt('程序仅支持Python3.4及以上版本运行,程序强制停止运行')
os._exit(0)

import signal
import requests
import importlib
import traceback
Expand All @@ -21,73 +22,82 @@
from requests.packages import urllib3
from multiprocessing import Process, Manager

local_dir = str((os.path.split(os.path.realpath(__file__))[0]).replace('\\', '/'))
errorlog_clean = open(local_dir + '/error.log', 'w').close()
ppid = os.getppid()
pid = os.getpid()

def error(pid, ppid):
system = str(platform.system())
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '程序运行出现错误,终止运行,错误信息已保存至程序目录下的error.log文件中')
with open(str((os.path.split(os.path.realpath(__file__))[0]).replace('\\', '/')) + '/error.log', 'a', encoding='utf-8') as f:

def error_log(local):
with open(local + '/error.log', 'a', encoding='utf-8') as f:
f.write(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + str(traceback.format_exc()) + '\n')
if system == 'Linux':
os.killpg(os.getpgid(int(pid)), signal.SIGTERM)
elif system == 'Windows':
os.system('taskkill /F /T /PID ' + str(pid))
else:
os.kill(int(ppid), signal.SIGTERM)
prt('程序运行出现错误,错误信息已保存至程序目录下的error.log文件中')


try:
import config
except:
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '配置获取异常,请检查配置文件是否存在/权限是否正确/语法是否有误')
error(pid, ppid)
prt("读取配置文件异常,程序终止运行,请检查配置文件是否存在或语法是否有问题")
error_log(local_dir)
os._exit(0)

if int(config.async_components):
import asyncio
run_as_async = 1
else:
run_as_async = 0

import itchat.content


def error(pid, ppid, errorlog_dir):
error_log(errorlog_dir)
prt('程序终止运行')
system = str(platform.system())
if system == 'Linux':
os.killpg(os.getpgid(int(pid)), signal.SIGTERM)
elif system == 'Windows':
os.system('taskkill /F /T /PID ' + str(pid))
else:
os.kill(int(ppid), signal.SIGTERM)


def config_update(value):
try:
config_path = value.get('local_dir') + '/config.py'
stat = os.stat(config_path)
old_st_mtime_ns = stat.st_mtime_ns
while 1:
try:
importlib.reload(config)
except:
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '配置获取异常,请检查配置文件是否存在/权限是否正确/语法是否有误')
error(value.get('pid'), value.get('ppid'))
break
shield_mode_update = '0'
newcfg = {'chat_push': str(config.chat_push), 'VoIP_push': str(config.VoIP_push), 'tdtt_alias': str(config.tdtt_alias),
'FarPush_regID': str(config.FarPush_regID), 'WirePusher_ID': str(config.WirePusher_ID),
'FarPush_Phone_Type': str(config.FarPush_Phone_Type), 'shield_mode': str(config.shield_mode),
'blacklist': list(config.blacklist), 'whitelist': list(config.whitelist), 'tdtt_interface': str(config.tdtt_interface),
'FarPush_interface': str(config.FarPush_interface), 'WirePusher_interface': str(config.WirePusher_interface)}
for a in newcfg.keys():
if str(a) == 'shield_mode':
if newcfg.get('shield_mode') != value.get('shield_mode'):
if int(newcfg.get('shield_mode')):
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '切换为白名单模式:群聊' + str(newcfg.get('whitelist')) + '以及非群聊的消息将会推送')
else:
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '切换为黑名单模式:' + str(newcfg.get('blacklist')) + '的消息将不会推送')
shield_mode_update = '1'
elif str(a) == 'whitelist':
if not int(shield_mode_update) and newcfg.get(a) != value.get(a) and int(newcfg.get('shield_mode')):
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '白名单更改:群聊' + str(newcfg.get(a)) + '以及非群聊的消息将会推送')
elif str(a) == 'blacklist':
if not int(shield_mode_update) and newcfg.get(a) != value.get(a) and not int(newcfg.get('shield_mode')):
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '黑名单更改:' + str(newcfg.get(a)) + '的消息将不会推送')
elif str(value.get(a)) != str(newcfg.get(a)):
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + a + '更改,新' + a + '值为' + newcfg.get(a))
value.update(newcfg)
stat = os.stat(config_path)
if stat.st_mtime_ns != old_st_mtime_ns:
old_st_mtime_ns = stat.st_mtime_ns
try:
importlib.reload(config)
newcfg = {'chat_push': str(config.chat_push), 'VoIP_push': str(config.VoIP_push), 'tdtt_alias': str(config.tdtt_alias),
'FarPush_regID': str(config.FarPush_regID), 'WirePusher_ID': str(config.WirePusher_ID),
'FarPush_Phone_Type': str(config.FarPush_Phone_Type), 'shield_mode': str(config.shield_mode),
'blacklist': list(config.blacklist), 'whitelist': list(config.whitelist), 'tdtt_interface': str(config.tdtt_interface),
'FarPush_interface': str(config.FarPush_interface), 'WirePusher_interface': str(config.WirePusher_interface)}
except:
prt('读取配置文件异常,请检查配置文件的语法是否有误或所需变量是否存在,程序使用最后一次正确的的配置')
error_log(value.get('local_dir'))
continue
for i in list(newcfg.keys()):
if str(value.get(i)) != str(newcfg.get(i)):
prt(str(i) + '更改,新' + str(i) + '值为' + str(newcfg.get(i)))
value.update(newcfg)
time.sleep(1)
except KeyboardInterrupt:
pass
prt('由于触发了KeyboardInterrupt(同时按下了Ctrl+C等情况),程序强制停止运行')
except FileNotFoundError:
prt('配置文件丢失,程序强制停止运行')
error(value.get('pid'), value.get('ppid'), value.get('local_dir'))
except:
error(value.get('pid'), value.get('ppid'))
error(value.get('pid'), value.get('ppid'), value.get('local_dir'))


def run(func):
if int(config.async_components):
if int(run_as_async):
asyncio.get_event_loop().run_until_complete(asyncio.gather(func))
else:
eval(str(func))
Expand All @@ -101,11 +111,11 @@ def data_send(url, **kwargs):
raise RuntimeError
except:
if str(i) == '4':
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '连续三次向接口发送数据超时/失败,可能是网络问题或接口失效,终止发送')
prt('连续三次向接口发送数据超时/失败,可能是网络问题或接口失效,终止发送')
break
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '向接口发送数据超时/失败,第' + str(i) + '次重试')
prt('向接口发送数据超时/失败,第' + str(i) + '次重试')
else:
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '成功向接口发送数据↑')
prt('成功向接口发送数据↑')
break


Expand All @@ -130,8 +140,8 @@ def simple_reply(msg):
itchat.content.REDENVELOPE: '[红包]',
itchat.content.EMOTICON: '[动画表情]',
itchat.content.SPLITTHEBILL: '[群收款]',
itchat.content.SHARING: '[未知卡片消息]',
itchat.content.UNDEFINED: '[未知消息类型]',
itchat.content.SHARING: '[卡片消息]',
itchat.content.UNDEFINED: '[发送了一条消息]',
itchat.content.VOIP: '[通话邀请]请及时打开微信查看',
itchat.content.SYSTEMNOTIFICATION: '[系统通知]',
itchat.content.ATTACHMENT: '[文件]' + str(msg.get('Text')),
Expand All @@ -145,11 +155,11 @@ def simple_reply(msg):
if int(msg.get('ChatRoom')):
typesymbol = str(msg.get('Name')) + ': ' + str(typesymbol)
if str(msg.get('Type')) == str(itchat.content.SHARING):
print('[未知卡片消息,请在github上提交issue]: AppMsgType=' + str(msg.get('Text')))
prt('[未知卡片消息,请在github上提交issue]: AppMsgType=' + str(msg.get('Text')))
elif str(msg.get('Type')) == str(itchat.content.UNDEFINED):
print('[未知消息类型,请在github上提交issue]: MsgType=' + str(msg.get('Text')))
prt('[未知消息类型,请在github上提交issue]: MsgType=' + str(msg.get('Text')))
else:
print(str(Name) + ': ' + str(typesymbol))
prt(str(Name) + ': ' + str(typesymbol))
if str(msg.get('Type')) == str(itchat.content.VOIP):
if str(value.get('VoIP_push')) == '1' and str(value.get('tdtt_alias')) != '':
data_send(str(value.get('tdtt_interface')), title='微信 ' + str(Name), content=str(typesymbol), alias=str(value.get('tdtt_alias')))
Expand All @@ -158,7 +168,7 @@ def simple_reply(msg):
elif str(value.get('VoIP_push')) == '3' and str(value.get('WirePusher_ID')) != '':
data_send(str(value.get('WirePusher_interface')), title='微信 ' + str(Name), message=str(typesymbol), id=str(value.get('WirePusher_ID')), type='WeChat_VoIP', action='weixin://')
else:
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '配置有误,请更改配置')
prt('配置有误,请更改配置')
else:
if str(value.get('chat_push')) == '1' and str(value.get('tdtt_alias')) != '':
data_send(str(value.get('tdtt_interface')), title='微信 ' + str(Name), content=str(typesymbol), alias=str(value.get('tdtt_alias')))
Expand All @@ -167,17 +177,16 @@ def simple_reply(msg):
elif str(value.get('chat_push')) == '3' and str(value.get('WirePusher_ID')) != '':
data_send(str(value.get('WirePusher_interface')), title='微信 ' + str(Name), message=str(typesymbol), id=str(value.get('WirePusher_ID')), type='WeChat_chat', action='weixin://')
else:
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '配置有误,请更改配置')
prt('配置有误,请更改配置')


if __name__ == '__main__':
try:
urllib3.disable_warnings()
errorlog_clean = open(str((os.path.split(os.path.realpath(__file__))[0]).replace('\\', '/')) + '/error.log', 'w').close()
run(itchat.check_login())
run(itchat.auto_login(hotReload=True, enableCmdQR=2))
value = Manager().dict()
value.update({'pid': str(pid), 'ppid': str(ppid), 'chat_push': str(config.chat_push),
value.update({'pid': str(pid), 'ppid': str(ppid), 'local_dir': str(local_dir), 'chat_push': str(config.chat_push),
'VoIP_push': str(config.VoIP_push), 'tdtt_alias': str(config.tdtt_alias),
'FarPush_regID': str(config.FarPush_regID), 'WirePusher_ID': str(config.WirePusher_ID),
'FarPush_Phone_Type': str(config.FarPush_Phone_Type), 'shield_mode': str(config.shield_mode),
Expand All @@ -187,11 +196,11 @@ def simple_reply(msg):
conf_update.daemon = True
conf_update.start()
if int(value.get('shield_mode')):
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '白名单模式:群聊' + str(value.get('whitelist')) + '以及非群聊的消息将会推送')
prt('白名单模式:群聊' + str(value.get('whitelist')) + '以及非群聊的消息将会推送')
else:
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '黑名单模式:' + str(value.get('blacklist')) + '的消息将不会推送')
prt('黑名单模式:' + str(value.get('blacklist')) + '的消息将不会推送')
run(itchat.run())
except KeyboardInterrupt:
print(str(datetime.now().strftime('[%Y.%m.%d %H:%M:%S] ')) + '由于键盘输入^C(ctrl+C),程序强制停止运行')
prt('由于触发了KeyboardInterrupt(同时按下了Ctrl+C等情况),程序强制停止运行')
except:
error(pid, ppid)
error(pid, ppid, local_dir)

0 comments on commit ec3e97a

Please sign in to comment.