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.
 
 
 

81 lines
2.1 KiB

  1. import logging
  2. import logging.handlers
  3. import pickle
  4. import random
  5. import re
  6. import time
  7. import urllib.parse
  8. import mastodon
  9. import requests
  10. import youtube
  11. USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
  12. logging.basicConfig(
  13. handlers=[logging.handlers.RotatingFileHandler('beatbot.log', maxBytes=100000, backupCount=10),
  14. logging.StreamHandler()],
  15. level=logging.INFO,
  16. format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
  17. datefmt='%Y-%m-%dT%H:%M:%S')
  18. LOGGER = logging.getLogger(__name__)
  19. def randline(fname):
  20. with open(fname) as afile:
  21. line = next(afile)
  22. for num, aline in enumerate(afile, 2):
  23. if random.randrange(num) == 0:
  24. line = aline
  25. return line.strip()
  26. def bot():
  27. genre = randline('genres.txt')
  28. verb1 = randline('1syllableverbs.txt')
  29. verb2 = randline('2syllableverbs.txt')
  30. search_term = f'+lofi {genre} +beats {verb1} {verb2}'
  31. text = f"lo-fi {genre} beats to {verb1} and {verb2} to".replace(' ', ' ')
  32. try:
  33. with open('seen-vids.dat', 'rb') as seen:
  34. seen_vids = pickle.load(seen)
  35. except Exception:
  36. seen_vids = set()
  37. video_ids = youtube.get_videos(search_term)
  38. yt_id = None
  39. random.shuffle(video_ids)
  40. # try to find a random video we haven't used before
  41. for vid in video_ids:
  42. if vid not in seen_vids:
  43. yt_id = vid
  44. break
  45. if not yt_id and video_ids:
  46. # nothing new, so just select a random one (list is already shuffled)
  47. yt_id = video_ids[0]
  48. if yt_id:
  49. text += f'\n\nhttps://youtube.com/watch?v={yt_id}'
  50. # remember that we used it already
  51. seen_vids.add(yt_id)
  52. with open('seen-vids.dat', 'wb') as seen:
  53. pickle.dump(seen_vids, seen)
  54. LOGGER.info(text)
  55. mdon = mastodon.Mastodon(
  56. access_token='token.secret',
  57. api_base_url='https://botsin.space')
  58. mdon.status_post(text)
  59. if __name__ == '__main__':
  60. bot()