import json, sys, re
from datetime import datetime, timedelta
esc_regex = re.compile(r"[#\*~=%!<>;\|\-\[\]\(\)\.`:\\\/]")
format_date = lambda x: (datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%fZ' if '.' in x else '%Y-%m-%dT%H:%M:%SZ') + timedelta(hours=3)).strftime('%d.%m.%Y %H:%M:%S')
format_time = lambda x: str(timedelta(seconds=x))
esc = lambda x: esc_regex.sub(lambda y: '\\' + y.group(0), x)
with open(sys.argv[1], 'r', encoding='utf-8') as f:
video = json.loads(f.read())
commenters = {}
for i in video['comments']:
commenter = tuple(i['commenter'].items())
commenters[commenter] = (commenters.get(commenter) or 0) + 1
print(f'## {esc(video["video"]["title"])} ({format_date(video["video"]["created_at"])})\n[Twitch запись](https://twitch.tv/videos/{video["video"]["id"]})')
headers = ['Сообщений', 'ID', 'Ник', 'Ник', 'Создан', 'Изменен']
print('|'.join(headers))
print('|'.join('-' for _ in headers))
for c, sent in filter(lambda x: x[1] >= 5, sorted(commenters.items(), key=lambda x: -x[1])):
c = dict(c)
print('|'.join(( str(sent), c['_id'], esc(c['name']), esc(c['display_name']), format_date(c['created_at']), format_date(c['updated_at']) )))
print('\n!>[Скрипт для парсинга](https://text.is/twitch-chat-parsing-script)')