youtube-url-corrector/bot.py

63 lines
1.8 KiB
Python
Raw Normal View History

2023-11-09 14:49:10 -05:00
import os
2024-01-18 22:35:33 -05:00
import re
2023-11-09 14:49:10 -05:00
from contextlib import suppress
2024-01-18 22:35:33 -05:00
from urllib.parse import urlparse, parse_qs
2023-11-09 14:49:10 -05:00
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
2024-02-19 17:55:17 -05:00
bot = commands.Bot(command_prefix="?", intents=intents)
2023-11-09 14:49:10 -05:00
2024-02-19 17:55:17 -05:00
PIPED_URL = os.getenv("PIPED_URL") + "/watch?v="
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
2023-11-09 14:49:10 -05:00
@bot.event
async def on_ready():
print("Ready!")
@bot.event
async def on_message(message):
regex = re.compile(
2024-02-19 17:55:17 -05:00
r"https://(music\.)?(www\.)?youtu(be)?\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)"
)
2023-11-09 14:49:10 -05:00
result = regex.search(message.content)
if result is not None:
youtube_url = result.group(0)
video_id = await get_youtube_id(youtube_url)
if video_id is not None:
2024-02-19 17:55:17 -05:00
await message.reply(
f"I think you meant {PIPED_URL}{video_id}.", mention_author=False
)
2023-11-09 14:49:10 -05:00
async def get_youtube_id(url: str, ignore_playlist=True) -> str:
query = urlparse(url)
2024-02-19 17:55:17 -05:00
if query.hostname == "youtu.be":
2024-01-18 23:02:24 -05:00
return query.path[1:]
2024-02-19 17:55:17 -05:00
if query.hostname in {"www.youtube.com", "youtube.com", "music.youtube.com"}:
2023-11-09 14:49:10 -05:00
if not ignore_playlist:
# use case: get playlist id not current video in playlist
with suppress(KeyError):
2024-02-19 17:55:17 -05:00
return parse_qs(query.query)["list"][0]
if query.path == "/watch":
return parse_qs(query.query)["v"][0]
if query.path[:7] == "/watch/":
return query.path.split("/")[1]
if query.path[:7] == "/embed/":
return query.path.split("/")[2]
if query.path[:3] == "/v/":
return query.path.split("/")[2]
if query.path[:8] == "/shorts/":
return query.path.split("/")[1]
2023-11-09 14:49:10 -05:00
bot.run(DISCORD_TOKEN)