challenge-heure.py 2.2 KB

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