-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom_yt_video_from_pls.py
73 lines (61 loc) · 2.35 KB
/
random_yt_video_from_pls.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import logging
import requests
import random
import googleapiclient.discovery
from urllib.parse import parse_qs, urlparse
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, CallbackContext
import configtb
# Replace with your own TELEGRAM API token, Google API key and YouTube playlist ID
api_token = configtb.api_token
key = configtb.key
playlist_id = configtb.playlist_id
url = f'https://www.youtube.com/playlist?list={playlist_id}'
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, I can give out random videos on the /video command")
async def echo(update: Update, context: CallbackContext) -> None:
#extract playlist id from url
query = parse_qs(urlparse(url).query, keep_blank_values=True)
playlist_id = query["list"][0]
print()
print(f'get all playlist items links from {playlist_id}')
print()
youtube = googleapiclient.discovery.build("youtube", "v3", developerKey = key)
request = youtube.playlistItems().list(
part = "snippet",
playlistId = playlist_id,
maxResults = 500
)
response = request.execute()
playlist_items = []
while request is not None:
response = request.execute()
playlist_items += response["items"]
request = youtube.playlistItems().list_next(request, response)
print()
print(f"total: {len(playlist_items)}")
print()
allList = ([
f'https://www.youtube.com/watch?v={t["snippet"]["resourceId"]["videoId"]}&list={playlist_id}&t=0s'
for t in playlist_items
])
x = random.choice(allList)
print()
print('RANDOM = ', x)
print()
await update.message.reply_text(str(x))
# Main function to handle incoming updates
def main() -> None:
"""Start the bot."""
application = ApplicationBuilder().token(api_token).build()
start_handler = CommandHandler('start', start)
application.add_handler(start_handler)
video_handler = CommandHandler('video', echo)
application.add_handler(video_handler)
application.run_polling()
if __name__ == '__main__':
main()