import
logging
import
os
import
subprocess
from
functools
import
wraps
import
time
import
uiautomation as auto
from
rich.console
import
Console
from
configparefile
import
ConfigFile
logging.basicConfig(level
=
logging.INFO,
filename
=
'wetchat_uploads.log'
,
filemode
=
'a'
,
format
=
'%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s'
,
datefmt
=
'%Y-%m-%d %H:%M:%S'
)
def
exception_handler(func):
@wraps
(func)
def
wrapper(
*
args,
*
*
kwargs):
try
:
return
func(
*
args,
*
*
kwargs)
except
Exception as e:
logging.error(e)
return
wrapper
def
is_configfile_exists():
_cfg
=
ConfigFile(
'wechat_config.ini'
)
if
not
_cfg.is_file_exist():
_cfg.set_config(
'WeChat_path'
,
'file_path'
,
'C:\\Program Files\\Tencent\\WeChat\\WeChat.exe'
)
_cfg.set_config(
'uploads_path'
,
'dir_path'
,
'C:\\Users\\Administrator\\Desktop\\uploads'
)
class
WechatUploads:
def
__init__(
self
)
-
>
None
:
self
.wx
=
auto.WindowControl(Name
=
'微信'
)
self
.cgf
=
ConfigFile(
'wechat_config.ini'
)
self
.console
=
Console()
self
.dir_uploads
=
os.path.normpath(
self
.cgf.read_config()[
'uploads_path'
][
'dir_path'
])
print
(
)
@exception_handler
def
is_WeChat_start(
self
):
if
self
.wx.Exists():
self
.wx.SwitchToThisWindow()
logging.info(
'微信已经启动'
)
return
True
else
:
subprocess.Popen(
self
.cgf.read_config().get(
'WeChat_path'
,
'file_path'
))
raise
Exception(
'微信未启动,请启动微信后再次运行该程序!'
)
@exception_handler
def
get_file_list(
self
, path):
file_list
=
[]
for
root, dirs, files
in
os.walk(path):
for
file
in
files:
file_list.append(os.path.join(root,
file
))
return
file_list
@exception_handler
def
upload_target(
self
, upload_target):
hh
=
self
.wx.ListControl(name
=
'会话'
).GetChildren()
for
h
in
hh:
if
h.Name
=
=
upload_target:
return
upload_target
raise
Exception(
'上传目标不存在'
)
def
wechat_api(
self
, file_name, target):
self
.wx.ListItemControl(Name
=
target).Click(simulateMove
=
False
)
self
.wx.ButtonControl(Name
=
'发送文件'
).Click(simulateMove
=
False
)
self
.wx.EditControl(Name
=
'文件名(N):'
).SendKeys(file_name)
self
.wx.SplitButtonControl(Name
=
'打开(O)'
).Click(simulateMove
=
False
)
self
.wx.ButtonControl(Name
=
'sendBtn'
).Click(simulateMove
=
False
)
def
upload_file(
self
, upload_target):
if
self
.is_WeChat_start():
_upload_target
=
self
.upload_target(upload_target)
_file_list
=
self
.get_file_list(
self
.dir_uploads)
for
_file
in
_file_list:
self
.wechat_api(_file, _upload_target)
now
=
time.strftime(
'%Y-%m-%d %H:%M:%S'
, time.localtime())
self
.console.
print
(
"[yellow]创建时间:{}\n文件:{} [green]状态:上传成功!"
.
format
(now, os.path.basename(_file)))
logging.info(
'{}上传成功'
.
format
(_file))
if
__name__
=
=
"__main__"
:
is_configfile_exists()
wx
=
WechatUploads()
target
=
input
(
'请输入上传目标(直接回车就默认为文件传输助手):'
).strip()
target
=
target
if
not
target
=
=
'
' else '
文件传输助手'
wx.upload_file(target)