├── .gitignore ├── Demo.py ├── README.md ├── FileOperate.py ├── AutoReplay.py ├── ParseDirAndUpload.py ├── NoteOperator.py ├── SaveWxMsg.py └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | ./.idea 2 | /.idea -------------------------------------------------------------------------------- /Demo.py: -------------------------------------------------------------------------------- 1 | import sys 2 | print(sys.version) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # wechatcrawler 2 | 微信爬虫,可以自动收集微信群的聊天记录 3 | 4 | python版本:2.7 / 3.6 5 | 6 | 需要安装的模块: 7 | 8 | pip install evernote 9 | 10 | pip install shutil 11 | 12 | pip install itchat 13 | -------------------------------------------------------------------------------- /FileOperate.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | import os 3 | import re 4 | 5 | ''' 6 | @author:llj 7 | 磁盘文件操作模块 8 | ''' 9 | # 当天存放路径 10 | RootPath = os.path.join('C:\\', 'wxhistory') 11 | # 文档存放路径 包含压缩包 12 | DocPath = 'doc' 13 | # 动态图存放路径 14 | GifPath = 'gif' 15 | # 图片存放路径 16 | ImgPaht = 'img' 17 | # 小视屏存放路径 18 | Mp4Path = 'mp4' 19 | # 语音存放路径 20 | Mp3Path = 'mp3' 21 | # 处理完后挪至该路径 22 | RootPath_History = os.path.join('C:\\', 'wxhistory_history') 23 | class FileOperate: 24 | 25 | 26 | # 创建笔记对应的文件夹 27 | def mkdir(self,path): 28 | # 去除首位空格 29 | path = path.strip() 30 | # 去除尾部 \ 符号 31 | path = path.rstrip("\\") 32 | # path_vedio = path + '\\vedio'; 33 | # path_pic = path + '\\img' 34 | 35 | # 判断路径是否存在 36 | # 存在 True 37 | # 不存在 False 38 | isExists = os.path.exists(path) 39 | # 判断结果 40 | if not isExists: 41 | # 如果不存在则创建目录 42 | # 创建目录操作函数 43 | # osmakedirs(path_vedio) 44 | # osmakedirs(path_pic) 45 | os.makedirs(path) 46 | print(path + ' 创建成功') 47 | return True 48 | else: 49 | # 如果目录存在则不创建,并提示目录已存在 50 | # print path + ' 目录已存在' 51 | return False 52 | 53 | # 创建文本文件 文件名为当天的日期2017-12-19am , pm这种格式 54 | def mkfile(self,filename): 55 | if os.path.exists(filename): 56 | pass; 57 | else: 58 | fobj=open(filename, 'w') 59 | fobj.close() 60 | def genTodaydirName(self,today_title): 61 | dirName='C:\\wxhistory\\'+today_title;#today_title 是日期加群名 62 | return dirName; 63 | 64 | # 写记录文件 65 | def updatefile(self,txtname,msgcontet): 66 | try: 67 | fobj = open(txtname, 'a') # 这里的a意思是追加,这样在加了之后就不会覆盖掉源文件中的内容,如果是w则会覆盖。 68 | fobj.write('\n') 69 | fobj.write(str(msgcontet.encode('utf-8').strip())) 70 | # fobj.write(b"\n"+ msgcontet.encode('utf-8')) # 这里的\n的意思是在源文件末尾换行,即新加内容另起一行插入。 71 | fobj.close() # 特别注意文件操作完毕后要close 72 | except IOError: 73 | print('*** file open error:') 74 | 75 | # # 定义要创建的目录 76 | # mkpath = "d:\\qttc\\web\\" 77 | # # 调用函数 78 | # mkdir(mkpath) 79 | 80 | 81 | 82 | 83 | def remove_emoji(self,text): 84 | emoji_pattern = re.compile( 85 | u"(\ud83d[\ude00-\ude4f])|" # emoticons 86 | u"(\ud83c[\udf00-\uffff])|" # symbols & pictographs (1 of 2) 87 | u"(\ud83d[\u0000-\uddff])|" # symbols & pictographs (2 of 2) 88 | u"(\ud83d[\ude80-\udeff])|" # transport & map symbols 89 | u"(\ud83c[\udde0-\uddff])" # flags (iOS) 90 | "+", flags=re.UNICODE) 91 | return emoji_pattern.sub(r'', text) 92 | if __name__ == '__main__': 93 | fo = FileOperate(); 94 | fo.createXml; -------------------------------------------------------------------------------- /AutoReplay.py: -------------------------------------------------------------------------------- 1 | #encoding: utf-8 2 | import itchat 3 | from itchat.content import * 4 | 5 | 6 | # 自动回复文本等类别消息 7 | # isGroupChat=False表示非群聊消息 8 | @itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING], isGroupChat=False) 9 | def text_reply(msg): 10 | itchat.send('这是我的小号,暂无调戏功能,有事请加我大号:Honlann', msg['FromUserName']) 11 | 12 | 13 | # 自动回复图片等类别消息 14 | # isGroupChat=False表示非群聊消息 15 | @itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO], isGroupChat=False) 16 | def download_files(msg): 17 | itchat.send('这是我的小号,暂无调戏功能,有事请加我大号:Honlann', msg['FromUserName']) 18 | 19 | 20 | # 自动处理添加好友申请 21 | @itchat.msg_register(FRIENDS) 22 | def add_friend(msg): 23 | itchat.add_friend(**msg['Text']) # 该操作会自动将新好友的消息录入,不需要重载通讯录 24 | itchat.send_msg(u'你好哇', msg['RecommendInfo']['UserName']) 25 | # 自动回复文本等类别的群聊消息 26 | # isGroupChat=True表示为群聊消息 27 | @itchat.msg_register([TEXT, SHARING], isGroupChat=True) 28 | def group_reply_text(msg): 29 | # 消息来自于哪个群聊 30 | chatroom_id = msg['FromUserName'] 31 | chatroom_id = msg['ToUserName'] 32 | # 发送者的昵称 33 | username = msg['ActualNickName'] 34 | # 消息并不是来自于需要同步的群 35 | if not chatroom_id in chatroom_ids: 36 | return 37 | if msg['Type'] == TEXT: 38 | content = msg['Content'] 39 | elif msg['Type'] == SHARING: 40 | content = msg['Text'] 41 | # 根据消息类型转发至其他需要同步消息的群聊 42 | if msg['Type'] == TEXT: 43 | for item in chatrooms: 44 | if not item['UserName'] == chatroom_id: 45 | if '君哥' in item['NickName']: 46 | print('找到') 47 | itchat.send('%s\n%s' % (username, msg['Content']), item['UserName']) 48 | elif msg['Type'] == SHARING: 49 | for item in chatrooms: 50 | if not item['UserName'] == chatroom_id: 51 | if '君哥' in item['NickName']: 52 | itchat.send('%s\n%s\n%s' % (username, msg['Text'], msg['Url']), item['UserName']) 53 | 54 | 55 | # 自动回复图片等类别的群聊消息 56 | # isGroupChat=True表示为群聊消息 57 | @itchat.msg_register([PICTURE, ATTACHMENT, VIDEO,RECORDING], isGroupChat=True) 58 | def group_reply_media(msg): 59 | # 消息来自于哪个群聊 60 | chatroom_id = msg['FromUserName'] 61 | chatroom_id = msg['ToUserName'] 62 | 63 | # 发送者的昵称 64 | username = msg['ActualNickName'] 65 | 66 | # 消息并不是来自于需要同步的群 67 | if not chatroom_id in chatroom_ids: 68 | return 69 | 70 | # 如果为gif图片则不转发 71 | if msg['FileName'][-4:] == '.gif': 72 | return 73 | 74 | # 下载图片等文件 75 | msg['Text'](msg['FileName']) 76 | # 转发至其他需要同步消息的群聊 77 | for item in chatrooms: 78 | if not item['UserName'] == chatroom_id: 79 | if '君哥' in item['NickName']: 80 | print('找到') 81 | itchat.send('@%s@%s@%s' % ({'Picture': 'img', 'Video': 'vid','Recording':'rcd'}.get(msg['Type'], 82 | 'fil'), 83 | msg['FileName']), 84 | item['UserName']) 85 | 86 | # 扫二维码登录 87 | itchat.auto_login(hotReload=True) 88 | # 获取所有通讯录中的群聊 89 | # 需要在微信中将需要同步的群聊都保存至通讯录 90 | chatrooms = itchat.get_chatrooms(update=True, contactOnly=True) 91 | chatroom_ids = [c['UserName'] for c in chatrooms] 92 | for c in chatrooms: 93 | if '微课' in c['NickName']: 94 | chatroom_ids=[c['UserName']] 95 | print('正在监测的群聊:', len(chatroom_ids), '个'); 96 | print(' '.join([item['NickName'] for item in chatrooms])); 97 | # 开始监测 98 | itchat.run() -------------------------------------------------------------------------------- /ParseDirAndUpload.py: -------------------------------------------------------------------------------- 1 | #encoding:utf-8 2 | import datetime 3 | import os 4 | import shutil 5 | import sys 6 | import time 7 | 8 | from NoteOperator import NoteOperator 9 | 10 | ''' 11 | @author:llj 12 | 项目模块2: 13 | 解析模块1生成的历史文件, 14 | 上传至印象笔记。 15 | 参数 h,m表示 每天的h时m分(24小时制) 16 | 即每天h:m执行一次定时任务 17 | ''' 18 | reload(sys) 19 | sys.setdefaultencoding('utf-8') 20 | h=23 21 | m=55 22 | # 当天存放路径 23 | RootPath = os.path.join('C:\\', 'wxhistory') 24 | # 文档存放路径 包含压缩包 25 | DocPath = 'doc' 26 | # 动态图存放路径 27 | GifPath = 'gif' 28 | # 图片存放路径 29 | ImgPaht = 'img' 30 | # 小视屏存放路径 31 | Mp4Path = 'mp4' 32 | # 语音存放路径 33 | Mp3Path = 'mp3' 34 | # 处理完后挪至该路径 35 | RootPath_History = os.path.join('C:\\', 'wxhistory_history') 36 | class ParseDirAndUpload: 37 | 38 | def __init__(self): 39 | print('启动') 40 | def task(self): 41 | noteOperator = NoteOperator(); 42 | rootpath_history = "C:\\wxhistory_history" 43 | #读取指定的目录D:\\wxhistory\\ 获取该目录下的所有的文件夹 44 | # rootpath="D:\\wxhistory" 45 | daysList = os.listdir(RootPath); 46 | timenow = time.strftime('%Y-%m-%d', time.localtime(time.time())); 47 | print(daysList) 48 | if(daysList): 49 | for everDayDir in daysList: 50 | print(everDayDir) 51 | print(timenow) 52 | if(everDayDir!=timenow): 53 | # 从得到的数组中选择昨天(任务在当天0点执行,这时候应该没有人聊天了)的文件,遍历改文件夹-->在印象笔记中创建notebooks(名字为日期名字) , 54 | notebook=noteOperator.createNotebook(everDayDir); 55 | # 需要再次遍历目录里的文件夹,获取归类对话后的文件夹 56 | daypath=os.path.join(RootPath,everDayDir);#拼合对应的路径 日期 57 | print(daypath) 58 | # daypathDir=os.listdir(daypath)#精确到每个聊天窗口 编码混乱 日期文件夹下面的列表 59 | # 不打算用listdir了,改为在各自的文件夹下面用一个txt存放对应的文件目录名 60 | unicodenamepath=os.path.join(daypath,'unicodename.txt'); 61 | if os.path.exists(unicodenamepath): 62 | for line in open(unicodenamepath, 'rb'): 63 | noteName = line.strip('\n') 64 | noteName = noteName.strip('\r') 65 | # for noteName in daypathDir: 66 | # print(unicode(noteName,'gb2312')) 67 | # noteName=noteName.decode('gbk')#解决中文乱码 这么做会将表情符变成? 68 | # noteName=line.decode().encode() 69 | #日期文件夹下面的子文件夹,每个文件夹为一个note , 将msgtxt里的文本信息中的附件类型的内容进行整理,切换对应的en-note,并upload对应的resource 70 | if noteName: 71 | noteOperator.createNote(notebook,noteName) 72 | #生成后,移动目录文件到历史文件夹 ,为了一致性, 移动的是日期目录 73 | 74 | # 判断是否已经存在文件夹,如果存在文件夹,需要挪走 75 | if(os.path.exists(os.path.join(RootPath_History,everDayDir))): 76 | print("已经存在文件夹,建议手工处理"+os.path.join(RootPath_History,everDayDir)) 77 | else: 78 | print('移动'+os.path.join(RootPath,everDayDir)); 79 | shutil.move(os.path.join(RootPath,everDayDir),RootPath_History); 80 | daysList = os.listdir(RootPath); 81 | if daysList: 82 | for dir in daysList: 83 | print('没移动成功'+dir) 84 | if __name__ == '__main__': 85 | e=ParseDirAndUpload() 86 | e.task() 87 | while True: 88 | now=datetime.datetime.now() 89 | if now.hour==2 and now.minute==28: 90 | e.task() 91 | time.sleep(60)#暂停1分钟,以避免还没完成 92 | print('执行完成') 93 | else: 94 | time.sleep(20) 95 | -------------------------------------------------------------------------------- /NoteOperator.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import hashlib 3 | import mimetypes 4 | import os 5 | import re 6 | import sys 7 | 8 | import Client_Production 9 | import evernote.edam.notestore.NoteStore as NoteStore 10 | import evernote.edam.type.ttypes as Types 11 | 12 | ''' 13 | @author:llj 14 | 笔记本操作模块 15 | ''' 16 | reload(sys) 17 | sys.setdefaultencoding('utf8') 18 | 19 | class NoteOperator: 20 | # 当天存放路径 21 | RootPath = os.path.join('C:\\', 'wxhistory') 22 | # 文档存放路径 包含压缩包 23 | DocPath = 'doc' 24 | # 动态图存放路径 25 | GifPath = 'gif' 26 | # 图片存放路径 27 | ImgPaht = 'img' 28 | # 小视屏存放路径 29 | Mp4Path = 'mp4' 30 | # 语音存放路径 31 | Mp3Path = 'mp3' 32 | # 处理完后挪至该路径 33 | RootPath_History = os.path.join('C:\\', 'wxhistory_history') 34 | flagPos = 0 35 | def remove_emoji(self,text): 36 | emoji_pattern = re.compile( 37 | u"(\ud83d[\ude00-\ude4f])|" # emoticons 38 | u"(\ud83c[\udf00-\uffff])|" # symbols & pictographs (1 of 2) 39 | u"(\ud83d[\u0000-\uddff])|" # symbols & pictographs (2 of 2) 40 | u"(\ud83d[\ude80-\udeff])|" # transport & map symbols 41 | u"(\ud83c[\udde0-\uddff])" # flags (iOS) 42 | "+", flags=re.UNICODE) 43 | return emoji_pattern.sub(r'', text) 44 | # 创建笔记本 45 | def createNotebook(self,notebookname): 46 | noteStore=Client_Production.noteStore; 47 | notebook = Types.Notebook(); 48 | notebook.name=notebookname; 49 | projectnotebookname='AllianceHero' 50 | notebook.stack=projectnotebookname 51 | # 搜索是否已经存在笔记本 52 | notebooks=noteStore.listNotebooks(Client_Production.token) 53 | isexistnotebook=False 54 | for nb in notebooks: 55 | if nb.name==notebookname: 56 | isexistnotebook=True 57 | notebook=nb 58 | # notebook. 59 | # note.notebookGuid = Client_Production.PROJECT_NOTES_GUID; 60 | if not isexistnotebook: 61 | notebook=noteStore.createNotebook(Client_Production.token,notebook); 62 | return notebook 63 | # 必须保证notename无乱码 64 | def createNote(self,notebook,notename): 65 | isexist = False; # 是否存在当天的笔记 目前认为不可能存在当天的笔记, 如果有一定要删除 66 | noteStore = Client_Production.client.get_note_store(); 67 | NOTE_SUFFIX = ''; 68 | NOTE_HEADER = ''; 69 | f = NoteStore.NoteFilter() 70 | 71 | msg_content=''; 72 | #根据路径,得到txt 73 | notetxtpath=self.RootPath+'/'+notebook.name+'/'+notebook.name+notename+"/"+notebook.name+notename+'.txt' 74 | # notetxtpath=notetxtpath.encode() 75 | print(notetxtpath) 76 | if os.path.exists(notetxtpath.decode('utf-8')): 77 | txtobj=open(notetxtpath.decode('utf-8'),'rb'); 78 | flag = 'attachmentFlag:' 79 | if txtobj: 80 | resources = [] 81 | for line in open(notetxtpath.decode('utf-8')): 82 | line = line.strip('\n') 83 | isattach = flag in line 84 | # 读取的内容,如果包含attachmentFlag: 截取后面的内容 85 | if isattach: 86 | flagPos = line.index(flag) 87 | filename = line[flagPos + len(flag):] 88 | data = Types.Data() 89 | filepath = self.RootPath + '/' + notebook.name + '/' + notebook.name+notename + filename; 90 | # 91 | filename = os.path.basename(filepath.encode('utf-8')) 92 | data = Types.Data() 93 | # try: 94 | # 必须保证文件名在生成的时候是gbk, 在读取的时候也是gbk , 没有在linux测试过 95 | # print(os.path.exists(filepath.decode('utf-8'))) 96 | # D:\wxhistory\2017 - 12 - 29\2017 - 12 - 29【联盟家长微课:郭宛灵微课\resources\mp4 97 | # 因为抬头已经用utf-8作为编码,open要求传入的path必须是unicode 98 | if os.path.exists(filepath.decode('utf-8')): 99 | data.body = open(filepath.decode('utf-8'), 'rb').read() 100 | data.size = len(data.body) 101 | data.bodyHash = hashlib.md5(data.body).hexdigest() 102 | resource = Types.Resource() 103 | resource.mime = mimetypes.guess_type(filename)[0] 104 | resource.data = data 105 | attr = Types.ResourceAttributes() 106 | attr.fileName = filename 107 | resource.attributes = attr 108 | hexhash = resource.data.bodyHash 109 | # gif肯定是表情符号,限制大小以免影响到阅读 110 | minetype = resource.mime 111 | msg_content += line[0:flagPos] + '
' 112 | if ('gif' in minetype): 113 | msg_content += "

" % \ 115 | (resource.mime, hexhash); 116 | else: 117 | msg_content += "
" % \ 119 | (resource.mime, hexhash); 120 | # 昵称 默认红色显示 121 | resources.append(resource) 122 | 123 | else: 124 | # p = re.compile(r'([\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f])') 125 | result, number =re.subn("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "",line) 126 | # msg_content += line.decode().encode() + '
' 127 | msg_content += result + '
' 128 | note = Types.Note(); 129 | note.notebookGuid = notebook.guid 130 | note.title = notename.encode() 131 | note.content = NOTE_HEADER; 132 | #过滤非法字符 133 | print("过滤前:"); 134 | print(msg_content) 135 | msg_content=re.sub(u"[\x00-\x08\x0b-\x0c\x0e-\x1f]+",u"",msg_content); 136 | errhref=''; 137 | msg_content=msg_content.replace(errhref,'#爬虫过滤错误信息#') 138 | note.content += msg_content.encode('utf-8') 139 | note.content += NOTE_SUFFIX 140 | note.resources = resources 141 | print("过滤后:") 142 | print(note.content) 143 | print('将要创建' +notebook.name+'//'+ notename) 144 | note = noteStore.createNote(Client_Production.token, note); 145 | print('创建完成') 146 | else: 147 | return 148 | 149 | 150 | # shutil.move(notename, rootpath_history) 151 | # if __name__ == '__main__': 152 | # e = NoteOperator(); 153 | # e.createNotebook('testtest5'); 154 | 155 | 156 | 157 | -------------------------------------------------------------------------------- /SaveWxMsg.py: -------------------------------------------------------------------------------- 1 | #encoding: utf-8 2 | import os 3 | import re 4 | import shutil 5 | import sys 6 | import time 7 | 8 | import itchat 9 | from itchat.content import * 10 | 11 | from FileOperate import FileOperate 12 | 13 | ''' 14 | @author:llj 15 | 项目模块1: 16 | 保存微信聊天记录到本地 17 | 一天一个文件夹 文件夹包含存放附件的resources文件夹以及一个聊天记录文本 18 | 文本内容以enml的格式进行存放,对于其中的附件类型的内容,将以特定的标识标识出来, 19 | 在上传到笔记的时候, 将对应的标记切换成笔记中的标签, 同时整个文件全部上传进去, 20 | 目前不考虑一个笔记的大小问题(因为单个笔记最大200m, 对于一个群一天能造成的大小,我觉得应该不会超过200m) 21 | 日期:2018年1月1日 增加功能 22 | 当微课群中拦截到指定老师的启动微课指令后, 将发言信息转发出去 23 | 当拦截到下课指令后,终止群发功能 24 | 该功能只是在一段时间内运行,可以考虑用线程的方式, 启动和停止线程进行,或者,通过变量的方式, 25 | 在发出上课指令后,该变量变化,用于后续判断,发出下课指令,恢复变量 26 | 27 | ''' 28 | fo=None; 29 | styleNcStart='' 30 | styleNcEnd='' 31 | # 当天存放路径 32 | RootPath = os.path.join('C:\\', 'wxhistory') 33 | # 文档存放路径 包含压缩包 34 | DocPath = 'doc' 35 | # 动态图存放路径 36 | GifPath = 'gif' 37 | # 图片存放路径 38 | ImgPath = 'img' 39 | # 小视屏存放路径 40 | Mp4Path = 'mp4' 41 | # 语音存放路径 42 | Mp3Path = 'mp3' 43 | # 处理完后挪至该路径 44 | RootPath_History = os.path.join('C:\\', 'wxhistory_history') 45 | 46 | def parseMsgAtt(msg_content, noteName, sendUsername, timenow): 47 | filename = os.path.basename(msg_content) 48 | filename = filename.encode() 49 | fileExtension = file_extension(filename) 50 | print(fileExtension) 51 | filename=filename.decode(); 52 | filedir = '' 53 | if '.gif' in fileExtension.lower(): 54 | filedir = '\\resources\\' + GifPath + '\\' + sendUsername + filename 55 | elif '.mp4' in fileExtension.lower(): 56 | filedir = '\\resources\\' + Mp4Path + '\\' + sendUsername + filename 57 | elif '.mp3' in fileExtension.lower(): 58 | filedir = '\\resources\\' + Mp3Path + '\\' + sendUsername + filename 59 | elif '.doc' in fileExtension.lower(): 60 | filedir = '\\resources\\' + DocPath + '\\' + sendUsername + filename 61 | elif '.txt' in fileExtension.lower(): 62 | filedir = '\\resources\\' + DocPath + '\\' + sendUsername + filename 63 | elif '.pdf' in fileExtension.lower(): 64 | filedir = '\\resources\\' + DocPath + '\\' + sendUsername + filename 65 | elif '.docx' in fileExtension.lower(): 66 | filedir = '\\resources\\' + DocPath + '\\' + sendUsername + filename 67 | elif '.xls' in fileExtension.lower(): 68 | filedir = '\\resources\\' + DocPath + '\\' + sendUsername + filename 69 | elif '.xlsx' in fileExtension.lower(): 70 | filedir = '\\resources\\' + DocPath + '\\' + sendUsername + filename 71 | elif '.ppt' in fileExtension.lower(): 72 | filedir = '\\resources\\' + DocPath + '\\' + sendUsername + filename 73 | elif '.pptx' in fileExtension.lower(): 74 | filedir = '\\resources\\' + DocPath + '\\' + sendUsername + filename 75 | elif '.zip' in fileExtension.lower(): 76 | filedir = '\\resources\\' + DocPath + '\\' + sendUsername + filename 77 | elif '.rar' in fileExtension.lower(): 78 | filedir = '\\resources\\' + DocPath + '\\' + sendUsername + filename 79 | else: 80 | filedir = '\\resources\\' + ImgPath + '\\' + sendUsername + filename 81 | destDir = fo.genTodaydirName(timenow + '\\' + noteName) + filedir 82 | print(destDir) 83 | shutil.move(filename, destDir); 84 | msg_content = styleNcStart + sendUsername + styleNcEnd + ':' + 'attachmentFlag:' + filedir; 85 | return msg_content 86 | 87 | 88 | def file_extension(filename): 89 | file_extension = os.path.splitext(filename)[1] 90 | return file_extension.decode(); 91 | 92 | 93 | #创建笔记本对应的目录结构和unicodename.txt 94 | def gen_unicodename(timenow, today_title_dir,chatroom): 95 | today_dir=fo.genTodaydirName(timenow)# 96 | fo.mkdir(today_dir); 97 | # 创建今天目录下的unicodename.txt用于保存每个文件夹 98 | if not os.path.exists(today_title_dir): 99 | fo.mkdir(today_title_dir) 100 | if not os.path.exists(os.path.join(today_dir, 'unicodename.txt')): 101 | fo.mkfile(os.path.join(today_dir, 'unicodename.txt')) 102 | fo.updatefile(os.path.join(today_dir, 'unicodename.txt'), chatroom) 103 | if not os.path.exists( today_title_dir+'\\resources'): 104 | fo.mkdir(today_title_dir + '\\resources'); 105 | if not os.path.exists( today_title_dir+'\\resources\\'+DocPath): 106 | fo.mkdir( today_title_dir+'\\resources\\'+DocPath); 107 | if not os.path.exists( today_title_dir+'\\resources\\'+GifPath): 108 | fo.mkdir( today_title_dir+'\\resources\\'+GifPath); 109 | if not os.path.exists(today_title_dir +'\\resources\\' + ImgPath): 110 | fo.mkdir( today_title_dir+'\\resources\\'+ImgPath); 111 | if not os.path.exists(today_title_dir +'\\resources\\' + Mp4Path): 112 | fo.mkdir( today_title_dir+'\\resources\\'+Mp4Path); 113 | if not os.path.exists(today_title_dir +'\\resources\\' + Mp3Path): 114 | fo.mkdir( today_title_dir+'\\resources\\'+Mp3Path); 115 | 116 | 117 | 118 | 119 | @itchat.msg_register(['Text', 'Note', 'Picture', 'Attachment', 'Card', 'Video','Recording','Sharing'], isFriendChat=False, 120 | isGroupChat=True, 121 | isMpChat=True) 122 | def print_content(msg): 123 | chatroom_id = msg['FromUserName'] 124 | # 群名 部分群名含有emoji码, 保存到磁盘的时候 默认格式保存,不需要特意编码 125 | chatroom_name = msg['User']['NickName']; 126 | #为了合理保存文件, 去掉emoji 缺点:有的群就是用emoji来区分的,这样做就没法区分不同的群了 127 | # chatroom_name=fo.remove_emoji(chatroom_name) 128 | # 发送者的昵称 群内名称 129 | sendUsername = msg['ActualNickName'] 130 | # sendUserNickname=msg['NickName'] 131 | # 真实名称ID 132 | username_id = msg['ActualUserName'] 133 | timenow = time.strftime('%Y-%m-%d', time.localtime(time.time())); 134 | # 验证是否已经创建当天的笔记 135 | noteName = timenow + chatroom_name; 136 | today_title_dir=fo.genTodaydirName(timenow+'\\'+noteName);#绝对路径 137 | gen_unicodename(timenow, today_title_dir,chatroom_name) 138 | txtname = today_title_dir + '\\' + noteName + ".txt" 139 | fo.mkfile(txtname) 140 | 141 | 142 | 143 | 144 | if msg['Type'] == 'Text' or msg['Type'] == 'Friends': 145 | msg_content = styleNcStart+sendUsername+styleNcEnd + ':' + msg['Text']; 146 | msg_content=msg_content.replace('&','&'); 147 | # 如果发送的消息是附件、视屏、图片、语音 148 | elif msg['Type'] == "Attachment" or msg['Type'] == "Video" or msg['Type'] == 'Picture' or msg[ 149 | 'Type'] == 'Recording': 150 | msg_content = msg['FileName'] # 内容就是他们的文件名 151 | msg['Text'](str(msg_content)) # 下载文件 152 | # filename = os.path.basename(msg_content) 153 | # shutil.move(filename, fo.genTodaydirName(timenow+'\\'+noteName)+'\\resources\\'+filename); 154 | # msg_content=styleNcStart+sendUsername+styleNcEnd + ':' +'attachmentFlag:'+filename; 155 | msg_content = parseMsgAtt(msg_content, noteName, sendUsername, timenow) 156 | 157 | elif msg['Type'] == 'Card': # 如果消息是推荐的名片 158 | msg_content = msg['RecommendInfo']['NickName'] + '的名片' # 内容就是推荐人的昵称和性别 159 | elif msg['Type'] == 'Map': # 如果消息为分享的位置信息 160 | x, y, location = re.search( 161 | "" + x.__str__() + " 经度->" + y.__str__() # 内容为详细的地址 164 | else: 165 | msg_content = r"" + location 166 | elif msg['Type'] == 'Sharing': # 如果消息为分享的音乐或者文章,详细的内容为文章的标题或者是分享的名字 167 | msg_content = styleNcStart+sendUsername+styleNcEnd + ':' + msg['Text']+''; 168 | msg_content += '
' 169 | else: 170 | msg_content=msg['Text'] 171 | print(msg_content) 172 | fo.updatefile(txtname,msg_content)#txtname为绝对路径 173 | #…………………… 174 | chatroom_id = msg['ToUserName'] 175 | 176 | # 发送者的昵称 177 | username = msg['ActualNickName'] 178 | 179 | # 消息并不是来自于需要同步的群 180 | if not chatroom_id in chatroom_ids: 181 | return 182 | 183 | # 根据消息类型转发至其他需要同步消息的群聊 184 | if msg['Type'] == TEXT: 185 | for item in chatrooms: 186 | if not item['UserName'] == chatroom_id: 187 | if '测试' in item['NickName']: 188 | print('找到') 189 | itchat.send('%s\n%s' % (username, msg['Content']), item['UserName']) 190 | elif msg['Type'] == SHARING: 191 | for item in chatrooms: 192 | if not item['UserName'] == chatroom_id: 193 | if '测试' in item['NickName']: 194 | itchat.send('%s\n%s\n%s' % (username, msg['Text'], msg['Url']), item['UserName']) 195 | else : 196 | # 如果为gif图片则不转发 197 | if msg['FileName'][-4:] == '.gif': 198 | return 199 | # 下载图片等文件 200 | msg['Text'](msg['FileName']) 201 | # 转发至其他需要同步消息的群聊 202 | for item in chatrooms: 203 | if not item['UserName'] == chatroom_id: 204 | if '测试' in item['NickName']: 205 | print('找到') 206 | # itchat.send(u'@%s\u2005I received: %s' % (msg['ActualNickName'], msg['Content']), 207 | itchat.send( msg['Content'], 208 | item['UserName']) 209 | # itchat.send('@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 210 | # 'fil'), 211 | # msg['FileName']), 212 | # item['UserName']) 213 | #………………………… 214 | 215 | if __name__ == '__main__': 216 | fo = FileOperate(); 217 | itchat.auto_login(hotReload=True) 218 | # 获取所有通讯录中的群聊 219 | # 需要在微信中将需要同步的群聊都保存至通讯录 220 | chatrooms = itchat.get_chatrooms(update=True, contactOnly=True) 221 | chatroom_ids = [c['UserName'] for c in chatrooms] 222 | for c in chatrooms: 223 | if '微课' in c['NickName']: 224 | chatroom_ids = [c['UserName']] 225 | itchat.run() 226 | print_content; 227 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------