users.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from config import ROOT_ID, logfile, users_db_file
  2. def get_id_from_log(string: str):
  3. try:
  4. user_id = string.split()[3]
  5. user_id = int(user_id)
  6. except Exception:
  7. return None
  8. else:
  9. return user_id
  10. class Users:
  11. def __init__(self) -> None:
  12. self.file_name = users_db_file
  13. self.users = self.__get_users_from_file()
  14. def __get_users_from_file(self) -> set:
  15. try:
  16. with open(self.file_name) as f:
  17. lines = f.readlines()
  18. except:
  19. return set()
  20. else:
  21. return set([int(l) for l in lines])
  22. def add_user(self, user_id: int) -> None:
  23. l = len(self.users)
  24. if user_id != ROOT_ID:
  25. self.users.add(user_id)
  26. if l < len(self.users):
  27. with open(self.file_name, 'a') as f:
  28. print(user_id, file=f)
  29. def from_log_to_db(self):
  30. with open(logfile, 'r') as f:
  31. users = [get_id_from_log(l)
  32. for l in f.readlines() if get_id_from_log(l)]
  33. for user in users:
  34. self.add_user(user)
  35. if __name__ == '__main__':
  36. db = Users()
  37. db.from_log_to_db()