kirisame commited on
Commit
0502916
·
1 Parent(s): 526e366

Add Discord JSON parser

Browse files
Files changed (1) hide show
  1. utils/discord_parse.py +54 -0
utils/discord_parse.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import argparse
3
+ import tqdm
4
+
5
+ from clean import clean
6
+
7
+ def format_channel(metadata):
8
+ return f'[Name: #{metadata["name"]}; Description: {metadata["topic"]};]'
9
+
10
+ def worker_parse(filename, **kwargs):
11
+ data = json.load(filename, 'r', encoding='utf-8'))
12
+ messages = data['messages']
13
+ metadata = data['channel']
14
+
15
+ print(format_channel(metadata))
16
+
17
+ msgs = []
18
+
19
+ for message in tqdm.tqdm(messages):
20
+ msg = ''
21
+ if 'anonymous' in kwargs and kwargs['anonymous']:
22
+ author = ''
23
+ else:
24
+ author = message['author']['name'] + ': '
25
+ if message['embeds']:
26
+ embed_content = ''
27
+ if message['embeds'][0]['title']:
28
+ embed_content = embed_content + f'Embed Title: {message["embeds"][0]["title"]};'
29
+ if message['embeds'][0]['description']:
30
+ desc = message['embeds'][0]['description']
31
+ if desc[-1] == '.':
32
+ desc = desc[:-1]
33
+ embed_content = embed_content + f' Embed Description: {desc};'
34
+ msg = f'[{embed_content}]'
35
+ if message['attachments']:
36
+ if message['attachments'][0]['url'].endswith(('.png', '.jpeg', '.jpg')) and message['attachments'][0]['url'].startswith('http'):
37
+ msg = '[Image attached]'
38
+ if message['content']:
39
+ msg = ''
40
+ msgs.append(f'{author}{clean(message["content"])}{msg}')
41
+
42
+ # replace json file extension with txt
43
+ filename = filename.replace('.json', '.txt')
44
+ with open(filename, 'w', encoding='utf-8') as f:
45
+ f.write('⁂\n'+format_channel(metadata)+'\n⁂\n')
46
+ f.write('\n'.join(msgs))
47
+
48
+ parser = argparse.ArgumentParser(description='Process Discord JSONs')
49
+ parser.add_argument('-f', '--file', type=str, help='file to process', required=True)
50
+ parser.add_argument('-a', '--anonymous', action='store_true', help='anonymous author')
51
+ args = parser.parse_args()
52
+
53
+ if __name__ == '__main__':
54
+ worker_parse(args.file, **args)