You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

87 regels
2.3 KiB

  1. """ Runner for the Lo-Fi Beats bot at https://botsin.space/@lofibeats """
  2. import logging
  3. import logging.handlers
  4. import os
  5. import pickle
  6. import random
  7. import mastodon
  8. import youtube
  9. logging.basicConfig(
  10. handlers=[logging.handlers.RotatingFileHandler('beatbot.log', maxBytes=100000, backupCount=10),
  11. logging.StreamHandler()],
  12. level=logging.INFO,
  13. format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
  14. datefmt='%Y-%m-%dT%H:%M:%S')
  15. LOGGER = logging.getLogger(__name__)
  16. def randline(fname):
  17. """ Get a random line from a file """
  18. with open(fname) as afile:
  19. line = next(afile)
  20. for num, aline in enumerate(afile, 2):
  21. if random.randrange(num) == 0:
  22. line = aline
  23. return line.strip()
  24. def bot():
  25. """ Run the bot """
  26. genre = randline('genres.txt')
  27. verb1 = randline('1syllableverbs.txt')
  28. verb2 = randline('2syllableverbs.txt')
  29. search_term = f'+lofi {genre} +beats {verb1} {verb2}'
  30. text = f"lo-fi {genre} beats to {verb1} and {verb2} to".replace(' ', ' ')
  31. seen_vids = set()
  32. try:
  33. with open('seen-vids.dat', 'rb') as seen:
  34. seen_vids = pickle.load(seen)
  35. except FileNotFoundError:
  36. LOGGER.info("Seen database not found")
  37. except pickle.UnpicklingError:
  38. LOGGER.exception("Seen database corrupted")
  39. video_ids = youtube.get_videos(search_term)
  40. LOGGER.info("%s: Found %d videos (%d new)", search_term,
  41. len(video_ids), len(set(video_ids) - seen_vids))
  42. yt_id = None
  43. random.shuffle(video_ids)
  44. # try to find a random video we haven't used before
  45. for vid in video_ids:
  46. if vid not in seen_vids:
  47. yt_id = vid
  48. break
  49. if not yt_id and video_ids:
  50. # nothing new, so just select a random one (list is already shuffled)
  51. yt_id = video_ids[0]
  52. if yt_id:
  53. text += f'\n\nhttps://youtube.com/watch?v={yt_id}'
  54. # remember that we used it already
  55. seen_vids.add(yt_id)
  56. with open('seen-vids.dat', 'wb') as seen:
  57. pickle.dump(seen_vids, seen)
  58. LOGGER.info(text)
  59. if not os.environ.get('BEATBOT_TESTING'):
  60. mdon = mastodon.Mastodon(
  61. access_token='token.secret',
  62. api_base_url='https://botsin.space')
  63. mdon.status_post(text)
  64. if __name__ == '__main__':
  65. bot()