buonanotte.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/env python3
  2. from mastodon import Mastodon, StreamListener
  3. from dateutil.tz import tzutc
  4. from dateutil import parser
  5. import datetime
  6. import re
  7. import csv
  8. API_URL = "https://botsin.space"
  9. regex = re.compile("([0-1]\d|[2][0-3]):[0-5]\d")
  10. class goodListener(StreamListener):
  11. def on_notification(self,notification):
  12. print("Notification received")
  13. account = notification["account"]["acct"]
  14. content = notification["status"]["content"]
  15. goodNight = regex.search(content)
  16. try:
  17. result = goodNight.group()
  18. with open("schedule.csv","a") as file:
  19. row = [result,account]
  20. writer = csv.writer(file)
  21. writer.writerow(row)
  22. mastodon.toot("Ciao @"+account+", ti ricordero' di andare a dormire alle ore "+result)
  23. except AttributeError:
  24. mastodon.toot("Ciao @"+account+", non ho capito a che ora vorresti andare a dormire")
  25. def handle_heartbeat(self):
  26. with open("schedule.csv","r") as file:
  27. reader = csv.reader(file)
  28. sentToBed = []
  29. for line,row in enumerate(reader):
  30. if parser.parse(row[0]) < datetime.datetime.now():
  31. mastodon.toot("Ciao @"+row[1]+" e' ora di andare a dormire! Buonanotte!")
  32. sentToBed.append(line)
  33. if (len(sentToBed) > 0):
  34. with open("schedule.csv","r") as file:
  35. lines = file.readlines()
  36. with open("schedule.csv","w") as file:
  37. for line,row in enumerate(lines):
  38. if not (line in sentToBed):
  39. file.write(row)
  40. if __name__ == "__main__":
  41. with open("token") as f:
  42. createapp = f.readlines()
  43. createapp = [x.strip() for x in createapp]
  44. TOKEN = createapp[0]
  45. mastodon = Mastodon(access_token = TOKEN, api_base_url = API_URL)
  46. listener = goodListener()
  47. mastodon.stream_user(listener)