Various Mastodon Bots

logger.py 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/python3
  2. import os
  3. import subprocess
  4. from datetime import date, timedelta
  5. from util import getAbsolutePath
  6. from format import formatBlogLog, formatLinkedTootLog, formatLocalTootLog, extractExternalLinks
  7. def main():
  8. logDir = getAbsolutePath(__file__, 'log/')
  9. logfile = "out.txt"
  10. logger = Logger(logDir, logfile)
  11. logger.archive()
  12. logger.logBlog('who', 'what', 'why')
  13. class Logger:
  14. blogPostsSection = '* New Posts'
  15. readSection = '* Stuff We Read'
  16. opinionSection = '* Short Takes'
  17. def __init__(self, logDir, logFile):
  18. self.logfile = str(logDir + logFile)
  19. def logBlog(self, title, author, link):
  20. logBlogString = formatBlogLog(title, author, link)
  21. self.__insertAfterString(self.blogPostsSection, logBlogString)
  22. def logToot(self, text, author):
  23. externalLinks = extractExternalLinks(text)
  24. if not externalLinks:
  25. self.__logLocalToot(text, author)
  26. else:
  27. self.__logLinkedToot(text, author)
  28. def __logLinkedToot(self, text, author):
  29. linkedTootString = formatLinkedTootLog(text, author)
  30. self.__insertAfterString(self.readSection, linkedTootString)
  31. def __logLocalToot(self, text, author):
  32. localTootString = formatLocalTootLog(text, author)
  33. self.__insertAfterString(self.opinionSection, localTootString)
  34. # WARNING: this function places all of self.logfile into memory,
  35. # could cause problems if file gets to big, which I don't
  36. # anticipate
  37. def __insertAfterString(self, seekString, insertString):
  38. with open(self.logfile, 'r') as log:
  39. logText = log.read()
  40. logText = logText.replace(seekString,
  41. seekString + '\n' + insertString, 1)
  42. with open(self.logfile, 'w') as log:
  43. log.write(logText)
  44. def archive(self):
  45. datepostfix = date.today().strftime("%y.%W")
  46. archiveFile = self.logfile + "." + datepostfix
  47. subprocess.run(['mv', self.logfile, archiveFile])
  48. self.__prepNewLogfile()
  49. def __prepNewLogfile(self):
  50. startDate = date.today()
  51. startDateString = startDate.strftime('%m/%d/%y')
  52. endDate = startDate + timedelta(days=6)
  53. endDateString = endDate.strftime('%m/%d/%y')
  54. with open(self.logfile, 'a') as log:
  55. log.write('Refactorings Roundup ' +
  56. startDateString +
  57. ' -- ' +
  58. endDateString + '\n')
  59. log.write(self.blogPostsSection + '\n')
  60. log.write(self.readSection + '\n')
  61. log.write(self.opinionSection + '\n')
  62. if __name__ == "__main__":
  63. main()