Compare commits

...

1 Commits

Author SHA1 Message Date
fluffy 418085c7ac Don't repeat videos if possible 2021-04-28 18:20:15 -07:00
2 changed files with 31 additions and 4 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
token.secret
seen-vids.dat

View File

@ -2,6 +2,7 @@ import mastodon
import random
import requests
import re
import pickle
def randline(fname):
with open(fname) as afile:
@ -19,11 +20,36 @@ def bot():
search_term = f'+lofi {genre} +beats {verb1} {verb2}'
text = f"lo-fi {genre} beats to {verb1} and {verb2} to"
try:
with open('seen-vids.dat', 'rb') as seen:
seen_vids = pickle.load(seen)
except Exception:
seen_vids = set()
query = requests.get(f'https://www.youtube.com/results?search_query={search_term}')
vids = re.findall(r'watch\?v=([^"]{11})"', query.text)
if vids:
print(f'{query.url} : {len(vids)} results')
text += f'\n\nhttps://youtube.com/watch?v={random.choice(vids)}'
video_ids = re.findall(r'watch\?v=([^"]{11})"', query.text)
yt_id = None
random.shuffle(video_ids)
# try to find a random video we haven't used before
for vid in video_ids:
if vid not in seen_vids:
yt_id = vid
break
if not yt_id and video_ids:
# nothing new, so just select a random one (list is already shuffled)
yt_id = video_ids[0]
if yt_id:
text += f'\n\nhttps://youtube.com/watch?v={yt_id}'
# remember that we used it already
seen_vids.add(yt_id)
with open('seen-vids.dat', 'wb') as seen:
pickle.dump(seen_vids, seen)
print(text)