Selaa lähdekoodia

Show the title and duration

Fixes #1
main
fluffy 5 kuukautta sitten
vanhempi
commit
a2253d902f
4 muutettua tiedostoa jossa 67 lisäystä ja 15 poistoa
  1. +35
    -9
      beatbot.py
  2. +16
    -1
      poetry.lock
  3. +1
    -0
      pyproject.toml
  4. +15
    -5
      youtube.py

+ 35
- 9
beatbot.py Näytä tiedosto

@@ -5,6 +5,7 @@ import logging.handlers
import os
import pickle
import random
import isodate

import mastodon

@@ -29,6 +30,30 @@ def randline(fname):
return line.strip()


def format_details(yt_id, snippet):
''' format the details of a video '''
text = f'https://youtube.com/watch?v={yt_id}'

try:
if snippet['liveBroadcastContent'] == 'live':
duration = ' (LIVE)'
else:
duration = ''
details = youtube.get_details(yt_id)
if details:
delta = isodate.parse_duration(details['duration'])
hours, rem = divmod(delta.seconds, 3600)
minutes, seconds = divmod(rem, 60)
duration = ' ('
if hours:
duration += f'{hours:d}:'
duration += f'{minutes:02d}:{seconds:02d})'
text += f' — {snippet["title"]}{duration}'
except RuntimeError:
LOGGER.exception("Unable to get video details")

return text

def bot():
""" Run the bot """
genre = randline('genres.txt')
@@ -49,26 +74,28 @@ def bot():

videos = youtube.get_videos(search_term)
LOGGER.info("%s: Found %d videos (%d new)", search_term,
len(videos), len(set(videos) - seen_vids))
len(videos), len({id for id,_ in videos} - seen_vids))

yt_id = None

random.shuffle(videos)

# try to find a random video we haven't used before
for (vid, title) in videos:
for (vid, snippet) in videos:
if vid not in seen_vids:
yt_id = vid
LOGGER.info("Using [https://youtube.com/watch?v=%s] %s", yt_id, title)
LOGGER.info("Using [https://youtube.com/watch?v=%s] %s",
yt_id, snippet['title'])
break

if not yt_id and videos:
# nothing new, so just select a random one (list is already shuffled)
(yt_id, title) = videos[0]
LOGGER.info("Reusing [https://youtube.com/watch?v=%s] %s", yt_id, title)
(yt_id, snippet) = videos[0]
LOGGER.info("Reusing [https://youtube.com/watch?v=%s] %s",
yt_id, snippet['title'])

if yt_id:
text += f'\n\nhttps://youtube.com/watch?v={yt_id}'
text += '\n\n' + format_details(yt_id, snippet)

# remember that we used it already
seen_vids.add(yt_id)
@@ -87,7 +114,6 @@ def bot():
if __name__ == '__main__':
try:
bot()
except Exception as e:
except Exception:
LOGGER.exception("Uncaught exception")
raise e

raise

+ 16
- 1
poetry.lock Näytä tiedosto

@@ -176,6 +176,17 @@ category = "main"
optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"

[[package]]
name = "isodate"
version = "0.6.0"
description = "An ISO 8601 date/time/duration parser and formatter"
category = "main"
optional = false
python-versions = "*"

[package.dependencies]
six = "*"

[[package]]
name = "isort"
version = "5.8.0"
@@ -411,7 +422,7 @@ python-versions = "*"
[metadata]
lock-version = "1.1"
python-versions = "^3.8"
content-hash = "55d7f5309ae3e4f48104088fb5ff5269f69d465253e4cdc23debebcfffea0d0e"
content-hash = "4500662333eb2f4225c0dbfcc8facc338e0d91d12d680bb441a5005db4518adc"

[metadata.files]
astroid = [
@@ -474,6 +485,10 @@ idna = [
{file = "idna-2.10-py2.py3-none-any.whl", hash = "sha256:b97d804b1e9b523befed77c48dacec60e6dcb0b5391d57af6a65a312a90648c0"},
{file = "idna-2.10.tar.gz", hash = "sha256:b307872f855b18632ce0c21c5e45be78c0ea7ae4c15c828c20788b26921eb3f6"},
]
isodate = [
{file = "isodate-0.6.0-py2.py3-none-any.whl", hash = "sha256:aa4d33c06640f5352aca96e4b81afd8ab3b47337cc12089822d6f322ac772c81"},
{file = "isodate-0.6.0.tar.gz", hash = "sha256:2e364a3d5759479cdb2d37cce6b9376ea504db2ff90252a2e5b7cc89cc9ff2d8"},
]
isort = [
{file = "isort-5.8.0-py3-none-any.whl", hash = "sha256:2bb1680aad211e3c9944dbce1d4ba09a989f04e238296c87fe2139faa26d655d"},
{file = "isort-5.8.0.tar.gz", hash = "sha256:0a943902919f65c5684ac4e0154b1ad4fac6dcaa5d9f3426b732f1c8b5419be6"},


+ 1
- 0
pyproject.toml Näytä tiedosto

@@ -9,6 +9,7 @@ python = "^3.8"
"Mastodon.py" = "^1.5.1"
wordfilter = "^0.2.6"
google-api-python-client = "^2.3.0"
isodate = "^0.6.0"

[tool.poetry.dev-dependencies]
autopep8 = "^1.5.6"


+ 15
- 5
youtube.py Näytä tiedosto

@@ -9,13 +9,13 @@ import config

LOGGER = logging.getLogger(__name__)

def get_videos(query):
""" Given a search query, return a list of video IDs """
youtube = googleapiclient.discovery.build('youtube', 'v3',
YTAPI = googleapiclient.discovery.build('youtube', 'v3',
developerKey=config.API_KEY,
cache_discovery=False)

request = youtube.search().list(
def get_videos(query):
""" Given a search query, return a list of video IDs """
request = YTAPI.search().list(
part="snippet",
q=query,
maxResults=100
@@ -27,7 +27,7 @@ def get_videos(query):
return []

wfilter = wordfilter.Wordfilter()
return [(item["id"]["videoId"], item['snippet'].get('title'))
return [(item["id"]["videoId"], item['snippet'])
for item in response['items']
if 'id' in item
and 'videoId' in item['id']
@@ -35,6 +35,16 @@ def get_videos(query):
item['snippet'].get('title', '')
+ item['snippet'].get('description', ''))]

def get_details(vid):
""" Given a video ID, get the content details """
request = YTAPI.videos().list(part="contentDetails",
id=vid)
response = request.execute()
for item in response['items']:
if item['id'] == vid:
return item['contentDetails']
return None


if __name__ == "__main__":
print(get_videos("+lofi beats to chill and relax to"))

Ladataan…
Peruuta
Tallenna