Add: ytlogin command to authorize against YouTube

This commit is contained in:
a 2024-10-23 04:35:02 +00:00
parent c6006e0e87
commit 84a2d6e31a

View file

@ -593,6 +593,65 @@ class Music(Cog):
logger.info(f"Message sent: Playing {len(tracks)} tracks.")
await self.play_next(ctx)
@command()
async def ytlogin(self, ctx: Context):
"""Print token and instructions for authorizing with YouTube"""
logger.info(f".ytlogin")
process = subprocess.Popen(
[
"yt-dlp",
"--netrc",
"--skip-download", # we don't care to actually download the video, we just wanna authorize
"https://www.youtube.com/watch?v=dQw4w9WgXcQ" # this can be anything, it just needs a youtube URL
],
stdout=subprocess.PIPE,
encoding="utf-8",
)
while True:
line = process.stdout.readline()
if not line:
logger.debug("Subprocess ran out of lines in stdout")
break
if "google.com" in line:
msg = await ctx.send(line)
if msg:
logger.info(f"Message sent: {line}")
break
timeout = time() + 30 # TODO: make this variable instead of hardcoded?
while (process.poll() is None) and (time() < timeout):
pass # this loop will break when the process exits with a return code, or when the timeout is exceeded
if process.poll() is None:
logger.debug("Process still hasn't exited yet, so we need to kill it and let the user know that the authorization process failed")
process.kill()
text = "Authorization process timed out."
msg = await ctx.send(text)
if msg:
logger.info(f"Message sent: {text}")
return
else:
logger.debug("Process has exited with a return code, so check if the return code indicates no errors.")
if process.returncode == 0:
text = "The process has finished with no errors, so you're probably logged in now."
msg = await ctx.send(text)
if msg:
logger.info(f"Message sent: {text}")
process.kill() # just in case
return
else:
process.kill() # just in case
out, err = process.communicate()
if err:
logger.error(f"An error occurred during the authorization process: {err}")
msg = await ctx.send(
f"An error occurred during the authorization process:\n",
f"```\n",
f"{err}",
f"```",
)
if msg:
logger.info(f"Message sent: An error occurred during the authorization process")
return
@command(aliases=['p', 'listen'])
async def play(self, ctx: Context, *, query: str = ""):
"""Add track(s) to queue"""
@ -866,9 +925,6 @@ ytdl_format_options = {
"extract_flat": True, # massive speedup for fetching metadata, at the cost of no upload date
#"cookiefile": "cookies.txt",
"cachedir": "cache",
"username": "oauth",
"password": "",
"usenetrc": True
}
username = getenv("YOUTUBE_USERNAME")
password = getenv("YOUTUBE_PASSWORD")
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)