Server Records/top users.py

See txt: ServerStats.txt
# top_users.py
#
# Author: 20wontons#6777
# Last updated: 23 February 2021
# Python: 3.8.6
# Known bugs: Only takes nicknames, need to find a way to account for changing nicknames.
# Change log: None
from pathlib import Path
def most_messages(p: Path):
 '''
 {User: [Number of Messages, Date]}
 '''
 the_file = None
 try:
 the_file = p.open('r', encoding = 'utf-8')
 user_dict = dict()
 
 for line in the_file:
 if len(line) == 11:
 date = line[:-1]
 continue
 if line.startswith('Top 5 Users') or line.startswith('Messages | Top 5 - Members'):
 if line.startswith('Messages | Top 5 - Members'):
 next(the_file)
 next(the_file)
 for _ in range(5):
 x = next(the_file)[:-1]
 user = x[x.find('@'):x.find(':')]
 mess = int(x[x.find(':')+2:x.find('messages')-1].replace(',',))
 if len(user_dict) == 10:
 least = sorted(user_dict.items(), key=lambda x: -x[1][0])[-1]
 if mess > least[1][0]:
 del user_dict[least[0]]
 else:
 continue
 if user not in user_dict:
 user_dict[user] = [mess, date]
 else:
 if mess > user_dict.get(user)[0]:
 user_dict[user] = [mess, date]
 else:
 continue
 return user_dict
 finally:
 if the_file != None:
 the_file.close()
def total_time(t: tuple):
 return t[0]*60 + t[1]
def most_voice(p: Path):
 '''
 {User: [(Hours, Minutes), Date]}
 '''
 
 the_file = None
 try:
 the_file = p.open('r', encoding = 'utf-8')
 user_dict = dict()
 
 for line in the_file:
 if len(line) == 11:
 date = line[:-1]
 continue
 if line.startswith('Voice | Top 5 - Members'):
 next(the_file)
 next(the_file)
 for _ in range(5):
 x = next(the_file)[:-1]
 h = m = 0
 
 user = x[x.find('@'):x.find(':')]
 if 'hours' in x:
 h = int(x[x.find(':')+2:x.find('hours')-1])
 if 'minutes' in x:
 m = int(x[x.find(',')+2:x.find('minutes')-1])
 
 if len(user_dict) == 10:
 least = sorted(user_dict.items(), key=lambda x: -total_time(x[1][0]))[-1]
 if total_time((h,m)) > total_time(least[1][0]):
 del user_dict[least[0]]
 else:
 continue
 if user not in user_dict:
 user_dict[user] = [(h,m), date]
 else:
 if total_time((h,m)) > total_time(user_dict.get(user)[0]):
 user_dict[user] = [(h,m), date]
 else:
 continue
 return user_dict
 finally:
 if the_file != None:
 the_file.close()
if __name__ == '__main__':
 m = most_messages(Path('ServerStats.txt'))
 print('== Top Messages Within 14 Days ==')
 for user, mess in sorted(m.items(), key=lambda x: -x[1][0]):
 print(mess[1], user + ':', mess[0])
 print()
 v = most_voice(Path('ServerStats.txt'))
 print('== Top Voice Time Within 14 Days ==')
 for user, voice in sorted(v.items(), key=lambda x: -total_time(x[1][0])):
 print(voice[1], user + ':', voice[0][0], 'hours,', voice[0][1], 'minutes')