一、环境说明
ntchat是通过hook方式获取聊天记录,发送信息的。目前只支持微信3.6.0.18版本,该版本的微信很多微信号都无法登录了(我的微信小号还可以登陆),不过可以使用cheatengine修改微信的版本号,再登陆上去。使用旧版本的微信还有一个好处,不会每天都掉线,好像也不会被封号。(目前我的微信小号已使用2年,持续获取微信群的聊天记录,自动回复部分信息,未被封号)
ntchat只能使用python3.7版本,在安装时需要注意。
ntchat只支持微信3.6.0.18的版本,下载地址:微信3.6.0.18下载
ntchat目前已经把开源代码都删掉了,不知道什么原因,主要使用的方法有这些

二、主程序代码
主程序主要就是登陆微信、发送信息、监听微信的聊天记录,获取聊天记录等。其他的一些方法,大家可以参照上面的图片调用。
# 主程序
import sys
import os
import datetime
import ntchat
import loghelper
import mysqlhelper
from xml.etree import ElementTree
#import threading
logger = loghelper.create_logger()
os.environ['NTCHAT_LOG'] = "ERROR"
# 格式化输出的时间
ISOTIMEFORMAT = '%Y-%m-%d %H:%M:%S'
# chinese :
wechat = ntchat.WeChat()
# 发送消息
def send_msg(wxid, msg):
# 发送消息函数
wechat.send_text(to_wxid=str(wxid), content=str(msg))
nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
print(f"{nowTime} 发送了一则消息\"{msg}\" 至 \"{wxid}\"")
logger.info(f"{nowTime} 发送了一则消息\"{msg}\" 至 \"{wxid}\"")
def LoginWx():
wechat.open(smart=True)
nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
print(f"{nowTime} 接管微信 等待登陆")
logger.info(f"{nowTime} 接管微信 等待登陆")
# 打开微信 等待登陆
wechat.wait_login()
nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
print(f"{nowTime} 接管微信成功")
logger.info(f"{nowTime} 接管微信成功")
def SyncWxRoom():
# get rooms and contacts list
rooms = wechat.get_rooms()
nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
print(f"{nowTime} 获取微信群群列表成功")
logger.info(f"{nowTime} 获取微信群群列表成功")
mysqlhelper.updateroom(rooms)
# contacts = wechat.get_contacts()
for item in rooms:
roomid = item["wxid"]
members = wechat.get_room_members(roomid)
nowTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
print(f"{nowTime} 获取聊天群联系人及群列表成功")
logger.info(f"{nowTime} 获取聊天群联系人及群列表成功")
mysqlhelper.updateroomcontact(members)
# print(members)
# get msg 文本消息
@wechat.msg_register(ntchat.MT_RECV_TEXT_MSG)
def on_recv_text_msg(wechat_instance: ntchat.WeChat, message):
try:
# 收到一条新消息
# 读取消息内容 发送着
data = message["data"]
mysqlhelper.insertroommsg(data)
print(data)
except Exception as e:
print('未知异常',e)
logger.info('未知异常', e)
# get msg 引用消息
@wechat.msg_register(ntchat.MT_RECV_OTHER_APP_MSG)
def on_recv_text_msg(wechat_instance: ntchat.WeChat, message):
try:
# 收到一条新消息
# 读取消息内容 发送着
data = message["data"]
if "@chatroom" in data["to_wxid"]:
roota = ElementTree.fromstring(data["raw_msg"]) # parse方法读取xml文件,得到元素树
msginfo = roota.findall("appmsg")[0].find("title").text
data["msg"] = msginfo
data["at_user_list"] = []
print(msginfo)
mysqlhelper.insertroommsg(data)
print(data)
except Exception as e:
print('未知异常',e)
logger.info('未知异常', e)
if __name__ == '__main__':
try:
LoginWx() #登陆微信
SyncWxRoom() #同步微信群和群成员
except Exception as e:
print('未知异常', e)
logger.info('未知异常', e)
try:
while True:
pass
except KeyboardInterrupt:
ntchat.exit_()
sys.exit()
三、数据库操作代码
获取的聊天记录直接就入库了,直接简单写了一下入库的脚本,有需要的自取。
import pymysql
import datetime
def updateroom(rooms):
# 建立数据库连接
db = pymysql.connect(host="127.0.0.1", user="root", password="C!oudC@m9uter",port=3308,database="db_ccmanager",charset="utf8mb4")
# 创建数据库的游标对象
cursor = db.cursor()
createtime = datetime.datetime.now()
for item in rooms:
roomid = item["wxid"]
cursor.execute("select * from tb_sv_wx_chatroom where wxroomid='%s'" % roomid)
room = cursor.fetchall()
if len(room) == 0:
# 向数据库插入数据:values括号里的值,需要用单引号,或者双引号
sqlinsert = "INSERT INTO tb_sv_wx_chatroom(wxroomid, avatar, is_manager, manager_wxid, nickname, total_member, Memo, CreateTime, CreateUserId, UpdateTime, UpdateUserId, RoomTag, Classify) VALUES('{}', '{}', '{}', '{}', '{}', {}, '', '{}', 1, '{}', 1, '', '');"
sqlinsert = sqlinsert.format(item["wxid"], item["avatar"], item["is_manager"], item["manager_wxid"],
item["nickname"],
item["total_member"], createtime, createtime)
cursor.execute(sqlinsert)
else:
#更新
sqlupdate = "update tb_sv_wx_chatroom set avatar='{}', is_manager='{}', manager_wxid='{}', nickname='{}', total_member={},UpdateTime='{}' WHERE wxroomid='{}';"
sqlupdate = sqlupdate.format(item["avatar"],item["is_manager"],item["manager_wxid"],item["nickname"],item["total_member"],createtime,item["wxid"])
cursor.execute(sqlupdate)
# 提交事务;增删改都需要提交事务,否则不会生效
db.commit()
# 关闭数据库
db.close()
def updateroomcontact(contact):
# 建立数据库连接
db = pymysql.connect(host="127.0.0.1", user="root", password="C!oudC@m9uter", port=3308, database="db_ccmanager",
charset="utf8mb4")
# 创建数据库的游标对象
cursor = db.cursor()
createtime = datetime.datetime.now()
total = contact["total"]
if total>0:
for item in contact["member_list"]:
item["group_wxid"]=contact["group_wxid"]
cursor.execute(" select * from tb_sv_wx_roomcontact where room_wxid ='%s' and wxuserid ='%s'" %(item["group_wxid"],item["wxid"]))
res = cursor.fetchall()
if len(res) == 0:
# 向数据库插入数据:values括号里的值,需要用单引号,或者双引号
sqlinsert = """INSERT INTO tb_sv_wx_roomcontact
(room_wxid, wxuserid, sex, nickname, remark, display_name, country, province, city,
Memo, CreateTime, CreateUserId, UpdateTime, UpdateUserId)
VALUES('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '', '{}', 1, '{}', 1); """
sqlinsert = sqlinsert.format(item["group_wxid"],item["wxid"], item["sex"], item["nickname"], item["remark"],
item["display_name"],item["country"],item["province"],item["city"], createtime, createtime)
cursor.execute(sqlinsert)
else:
# 更新
sqlupdate = ("""update tb_sv_wx_roomcontact set sex='{}', nickname='{}', remark='{}', display_name='{}', country='{}',
province='{}',city='{}',UpdateTime='{}' WHERE room_wxid='{}' and wxuserid='{}';""")
sqlupdate = sqlupdate.format(item["sex"], item["nickname"], item["remark"],item["display_name"],item["country"],
item["province"],item["city"], createtime,item["group_wxid"],item["wxid"])
cursor.execute(sqlupdate)
# 提交事务;增删改都需要提交事务,否则不会生效
db.commit()
# 关闭数据库
db.close()
def insertroommsg(item):
# 建立数据库连接
db = pymysql.connect(host="127.0.0.1", user="root", password="C!oudC@m9uter", port=3308, database="db_ccmanager",
charset="utf8mb4")
# 创建数据库的游标对象
cursor = db.cursor()
createtime = datetime.datetime.now()
sqlinsert = """INSERT INTO tb_sv_wx_roommsg
(msgid, room_wxid, from_wxid, to_wxid, wx_type, msg, at_user_list, status,
Memo, QuestionId, CreateTime, CreateUserId, UpdateTime, UpdateUserId)
VALUES ('{}', '{}', '{}', '{}', '{}', '{}', '{}', 1,
'', null, '{}', 1, '{}', 1); """
sqlinsert = sqlinsert.format(item["msgid"], item["room_wxid"], item["from_wxid"], item["to_wxid"], item["wx_type"],
item["msg"], ','.join(map(str, item["at_user_list"])),createtime, createtime)
cursor.execute(sqlinsert)
# 提交事务;增删改都需要提交事务,否则不会生效
db.commit()
# 关闭数据库
db.close()
四、日志模块代码
为了方便排查问题,增加了日志模块
import logging
import os
import sys
import time
from logging.handlers import TimedRotatingFileHandler
# 定义默认日志格式
"""
%(asctime)s :日志记录的时间
%(levelname)s :日志级别
%(message)s :日志消息的内容
%(name)s :日志记录器的名称
%(filename)s :源代码文件名称
%(lineno)d :源代码文件中的行号
%(funcName)s :调用日志记录的函数名
"""
LOG_FORMAT = "%(asctime)s %(levelname)s [%(filename)s: %(lineno)d] %(message)s"
# 定义日志全局记录级别: DEBUG < INFO < WARNING < ERROR < CRITICAL
WRITE_LEVEL = logging.DEBUG
# 定义输出控制台日志级别
CONSOLE_LEVEL = logging.INFO
# 定义输出文件日志级别
FILE_LEVEL = logging.INFO
# 日志文件存放路径,如不需要路径,填写 None
FILE_PATH = "logs"
# 日志文件名称
#LOG_FILE_NAME = "mylog.log"
LOG_FILE_NAME = '{}.log'.format(time.strftime('%Y-%m-%d'))
# 定义默认日志切割的时间单位,比如 'S'(秒)、'M'(分)、'H'(小时)、'D'(天)等
WHEN = "D"
# 定义默认日志文件切割的时间间隔,例如当 when='H' 且 interval=1 时,表示每隔一个小时进行一次切割,并生成一个新的日志文件
INTERVAL = 1
# 定义默认保留旧日志文件的个数(如果超过这个数量,则会自动删除最早的日志文件),默认值为 0,表示不自动删除旧日志文件
BACKUPCOUNT = 0
def create_logger(logger_name=None):
"""日志记录模块"""
# 获取当前脚本所在的目录路径。该方法获取不正确时,使用方法二:os.path.realpath(sys.argv[0])
script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
if FILE_PATH:
# 拼接日志文件完整路径
log_filename = os.path.join(script_dir, FILE_PATH, LOG_FILE_NAME)
# 如果指定路径不存在,则尝试创建路径
if not os.path.exists(os.path.join(script_dir, FILE_PATH)):
os.makedirs(os.path.join(script_dir, FILE_PATH))
else:
# 拼接日志文件完整路径
log_filename = os.path.join(script_dir, LOG_FILE_NAME)
# 创建 Logger 实例,如果传入 logger_name 参数,则使用该名称创建 Logger,否则使用根 Logger
logger = logging.getLogger(logger_name)
logger.setLevel(WRITE_LEVEL)
# 配置控制台输出
console_handler = logging.StreamHandler() # 创建 StreamHandler 实例,即将日志输出到控制台的处理器
console_handler.setLevel(CONSOLE_LEVEL)
console_handler.setFormatter(logging.Formatter(LOG_FORMAT))
logger.addHandler(console_handler)
# 配置文件输出
file_handler = TimedRotatingFileHandler(log_filename,
when=WHEN,
interval=INTERVAL,
backupCount=BACKUPCOUNT,
encoding='utf-8') # 创建 TimedRotatingFileHandler 实例,即将日志输出到文件的处理器
file_handler.setLevel(FILE_LEVEL)
file_handler.setFormatter(logging.Formatter(LOG_FORMAT))
logger.addHandler(file_handler)
return logger
五、打包命令
pyinstaller --clean -F -w main.py --collect-data=ntchat 打包成功

176




被折叠的 条评论
为什么被折叠?



