sendSMS.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import datetime
  2. import time
  3. import random
  4. import os
  5. import pandas as pd
  6. from sms import prepare_sms
  7. LOCK_PATH = "output\\alarms.lock"
  8. ALARM_DB = "output\\alarms.feather"
  9. WAIT_FOR_NEXT_MESSAGE = 60
  10. def process_dataframe(df):
  11. now = datetime.datetime.now()
  12. records = df.to_dict("records")
  13. for alarm in records:
  14. if (~alarm["is_sent"]) & (alarm["time"] < now):
  15. try:
  16. prepare_sms(alarm["phone_number"], alarm["content"], True)
  17. # Update alarms status
  18. alarm["is_sent"] = True
  19. # print("SMS send to " + alarm["phone_number"])
  20. # sleep to avoid reaching
  21. time.sleep(random.randint(1, 8))
  22. except Exception as exp:
  23. print(
  24. "Echec lors de l'envoie du SMS au " + alarm["phone_number"],
  25. exp,
  26. )
  27. # Transform back the data into dataframe
  28. return pd.DataFrame.from_dict(records)
  29. def main():
  30. if os.path.exists(LOCK_PATH):
  31. print("The program is already running")
  32. else:
  33. # Touch the Lock File
  34. with open(LOCK_PATH, "w") as f:
  35. f.write("")
  36. try:
  37. # Read data from database
  38. df = pd.read_feather(ALARM_DB)
  39. completion = df.is_sent.mean()
  40. print(f"Message send {completion*100:02.0f}%")
  41. try:
  42. while True:
  43. df = process_dataframe(df)
  44. df.to_feather(ALARM_DB)
  45. now = datetime.datetime.now()
  46. sms_sent = df.is_sent.mean()
  47. if sms_sent > completion:
  48. print(f"Message send {sms_sent*100:02.0f}%")
  49. completion = sms_sent
  50. if completion == 1:
  51. break
  52. delta = df[~df.is_sent].time.min() - now
  53. time.sleep(delta.total_seconds() + 1)
  54. except KeyboardInterrupt:
  55. pass
  56. finally:
  57. df.to_feather(ALARM_DB)
  58. finally:
  59. print("The program is done")
  60. # Remove the lock file
  61. os.remove(LOCK_PATH)
  62. if __name__ == "__main__":
  63. main()