-
파이썬 json으로 만든 인스타그램 DM txt파일로 내보내기코딩 2022. 6. 2. 13:38
import json import datetime day = ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'] def decode_utf(str): return str.encode('latin1').decode('unicode-escape').encode('latin1').decode('utf-8') def timemstodatetime(timems): daynum = int(datetime.datetime.fromtimestamp(timems/1000.0).strftime("%w")) pmam = ' 오전 ' if datetime.datetime.fromtimestamp(timems/1000.0).strftime("%p") == "AM" else ' 오후 ' return (datetime.datetime.fromtimestamp(timems/1000.0)).strftime("%Y년 %m월 %d일 ") + day[daynum] + pmam + (datetime.datetime.fromtimestamp(timems/1000.0)).strftime("%I시 %M분") def jsontodm(json): key = ['name', 'time', 'content', 'reaction'] value = [decode_utf(json['sender_name']), timemstodatetime(json['timestamp_ms'])] if json['type'] == "Generic": try: if json['content'] == "Liked a message": content = "메세지를 좋아합니다." else: content = decode_utf(json['content']) except: try: if json['photos'] != []: content = "(사진)" except: content = "(볼 수 없는 메세지)" else: try: content = "스토리에 답장을 보냈습니다 : " + decode_utf(json['content']) except: try: content = "공유 : " + json['share']['link'] except: content = "공유 : 스토리 또는 링크를 볼 수 없음." value.append(content) try: value.append(str([decode_utf(json['reactions'][i]['reaction']) for i in range(len(json['reactions'])//2)])) except: value.append("N") return dict(zip(key, value)) file_list = ["message_1.json"] // 파일 이름 넣기 with open(file_list[0], "r", encoding="utf-8") as File: json_data = json.loads(File.read()) dm = json_data['messages'] for file in file_list[1::]: with open(file, "r", encoding="utf-8") as File: dm = dm + json.loads(File.read())['messages'] title = decode_utf(json_data['title']) participants = ["[" + decode_utf(json_data['participants'][i]['name']) + "]" for i in range(len(json_data['participants']))] last_dm = timemstodatetime(dm[0]['timestamp_ms']) Predm = {'name' : "N", 'time' : "N"} for splited_dm in dm[::-1]: print(jsontodm(splited_dm)) with open("DM.txt", "w", encoding="utf-8") as Output: Output.write(title + " 인스타그램 DM\n참여자 : " + ", ".join(participants) + "\n마지막 대화 : " + last_dm) for splited_dm in dm[::-1]: splited_dm = jsontodm(splited_dm) if Predm['name'] != splited_dm['name'] or Predm['time'] != splited_dm['time']: Output.write("\n[" + splited_dm['name'] + "] " + splited_dm['time']) Predm = splited_dm Output.write("\n" + (str(splited_dm['reaction'][2:-2].replace(",","")) if splited_dm['reaction'] != "N" else "") + "\t" + splited_dm['content'].replace("\n", "\n\t"))
인스타그램 DM을 하다보면 DM이 아주 많이 쌓여서 스크롤만 몇분 하기도 한다.
아니언제끝나는데 무려 인스타그램 DM은 대화 검색을 지원하지 않아서 제일 상단으로 올라가는 꼼수란 존재하지 않는다.
그 불편함을 해소하기 위해서 인스타그램은 계정 데이터 파일을 json 형태로 다운로드 받을 수 있게 해주지만, 그것을 보려면 전용 뷰어가 필요하고, 가독성도 구리기 때문에, 해당 코드를 제작했다.
인스타그램 계정 데이터 다운로드에 관해서는 인터넷에 검색하면 수두룩하게 나오니 패스하겠고,
txt파일로 내보내기 위해서는 message 폴더 안의 inbox 폴더에 그동안 사람들과 했던 DM이 폴더 형태로 정리되어 있는데, 그 안에 있는 message_1.json 파일이 필요하다 (가끔씩 DM을 많이 했을 경우, 2, 3, 4.. 이렇게 가기도 한다.)
위 코드를 .py형태로 만들고, message_1.json이 있는 폴더에 넣어서 실행시키면 DM.txt라는 파일이 나오고 그것이 끝이다.
만약에 message json이 하나가 아니라면, 위 file_list를 수정해서 file_list = ["message_1.json", "message_2.json"] 이런식으로 만들면 된다.
txt파일 양식은
### 인스타그램 DM 참여자 : [###], [&&&] 마지막 대화 : 2022년 03월 15일 화요일 오후 02시 50분 [###] 2022년 2월 1일 화요일 오후 02시 47분 메세지 입니다.
이런식으로 나온다.
사실 이 코드 짜는데 진짜 긴박하게 짜서 코드가 많이 구릴수 있다. 만약 구린점을 발견했다면, 본인이 수정하는건 어떨까?
'코딩' 카테고리의 다른 글
파이썬 requests로 만든 로또 번호 예측 (0) 2022.06.27 파이썬 List로 만든 숫자 한글 변환기 (0) 2022.06.14 파이썬 random으로 만든 로또 시뮬레이터 (0) 2021.05.16 파이썬 file write로 만든 ".py"파일 쉽게 만들기 (0) 2021.05.12 파이썬 file open으로 만든 카카오톡 단톡방 채팅 분석 (0) 2021.05.12