challenge-heure.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/python3
  2. import json
  3. import sys
  4. from datetime import datetime
  5. def import_array(filename):
  6. # Load the JSON file
  7. with open(filename, 'r') as f:
  8. data = json.load(f)
  9. # Access the "messages" array
  10. array = data['messages']
  11. return array
  12. def check_challenge_win(message, hour, minute):
  13. # Check that the message has text and that the text is "1337"
  14. if "text" in message and message["text"] == hour + minute:
  15. # Check if the message was edited, return false
  16. if "edited" in message:
  17. return False
  18. else:
  19. # get the hour and minutes from the date
  20. dt = datetime.fromtimestamp(int(message["date_unixtime"]))
  21. #finally, check if the hour and minute corresponds to the text of the message
  22. if (dt.hour == int(hour) and dt.minute == int(minute)):
  23. return True
  24. else:
  25. return False
  26. def analyze_messages(messages, hour, minute):
  27. # Initialize the dict that we will return
  28. wins = {}
  29. # check the messages
  30. for message in messages:
  31. if(check_challenge_win(message, hour, minute)):
  32. #print("Message gagnant de " + message["from"] + " le " + message["date"])
  33. #If it's the first win, add the key with value 1
  34. if message["from"] not in wins:
  35. wins[message["from"]] = 1
  36. # Else, add 1 to the number of wins
  37. else:
  38. wins[message["from"]] += 1
  39. return wins
  40. def verify_time_string(time):
  41. # Check that the time string is made of 4 digits
  42. if not(time.isdigit() and len(time) ==4):
  43. print("Erreur : format de chaine non valide", file=sys.stderr)
  44. return False
  45. # Check that the hour and minute numbers are valid
  46. elif not (0 <= int(time[:2]) < 24 and 0 <= int(time[2:]) < 60):
  47. print("Erreur : heure non valide", file=sys.stderr)
  48. return False
  49. else:
  50. return True
  51. def main():
  52. # Get the file name from the first command line argument
  53. filename = sys.argv[1]
  54. # Get the time chosen for the challenge (1337,1312, 2222, etc.)
  55. time = sys.argv[2]
  56. # Verify that the time string is a valid time of day
  57. if verify_time_string(time):
  58. hour = time[:2]
  59. minute = time[2:]
  60. else:
  61. quit()
  62. # Import the array from the JSON file
  63. messages = import_array(filename)
  64. # create a dict containing the number of wins for each sender
  65. wins = analyze_messages(messages, hour, minute)
  66. # sort and print the resulting wins dict
  67. sorted_wins = sorted(wins.items(), key=lambda x:x[1], reverse=True)
  68. print(sorted_wins)
  69. if __name__ == '__main__':
  70. main()