Compare commits

...

1 Commits

Author SHA1 Message Date
fluffy a0cabc329e Don't repeat videos if possible 2021-04-28 18:11:06 -07:00
2 changed files with 32 additions and 5 deletions

1
.gitignore vendored
View File

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

View File

@ -2,6 +2,7 @@ import mastodon
import random import random
import requests import requests
import re import re
import pickle
def randline(fname): def randline(fname):
with open(fname) as afile: with open(fname) as afile:
@ -19,18 +20,43 @@ def bot():
search_term = f'+lofi {genre} +beats {verb1} {verb2}' search_term = f'+lofi {genre} +beats {verb1} {verb2}'
text = f"lo-fi {genre} beats to {verb1} and {verb2} to" 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}') query = requests.get(f'https://www.youtube.com/results?search_query={search_term}')
vids = re.findall(r'watch\?v=([^"]{11})"', query.text) video_ids = re.findall(r'watch\?v=([^"]{11})"', query.text)
if vids:
print(f'{query.url} : {len(vids)} results') yt_id = None
text += f'\n\nhttps://youtube.com/watch?v={random.choice(vids)}'
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) print(text)
mdon = mastodon.Mastodon( mdon = mastodon.Mastodon(
access_token='token.secret', access_token='token.secret',
api_base_url='https://botsin.space') api_base_url='https://botsin.space')
mdon.status_post(beats) # mdon.status_post(beats)
if __name__ == '__main__': if __name__ == '__main__':
bot() bot()