Made the plex functions use buttons

This commit is contained in:
NikolajDanger
2021-08-18 21:12:32 +02:00
parent ae71ff631d
commit 3819e56cd6
6 changed files with 305 additions and 307 deletions

View File

@ -1,11 +1,15 @@
"""Plex integration with the bot."""
from math import floor, ceil
import time
import json
import asyncio
import requests
import imdb
import discord
import xmltodict
from discord_slash.utils.manage_components import (create_button,
create_actionrow)
from discord_slash.model import ButtonStyle
class Plex():
"""Container for Plex functions and commands."""
@ -64,88 +68,102 @@ class Plex():
colour=0x00FF00
)
message = await ctx.send(embed=embed)
message_data = {"message_id":message.id,"imdb_ids":imdb_ids}
file_path = f"gwendolyn/resources/plex/old_message{ctx.channel.id}"
with open(file_path,"w") as file_pointer:
json.dump(message_data, file_pointer)
buttons = []
if len(movies) == 1:
await message.add_reaction("✔️")
buttons.append(create_button(
style=ButtonStyle.green,
label="",
custom_id=f"plex:movie:{imdb_ids[0]}"
)
)
else:
for i in range(len(movies)):
await message.add_reaction(["1","2","3","4","5"][i])
buttons.append(
create_button(
style=ButtonStyle.blue,
label=str(i+1),
custom_id=f"plex:movie:{imdb_ids[i]}"
)
)
buttons.append(create_button(
style=ButtonStyle.red,
label="X",
custom_id="plex:movie:"
)
)
action_rows = []
for i in range(((len(buttons)-1)//5)+1):
action_rows.append(
create_actionrow(
*buttons[(i*5):(min(len(buttons),i*5+5))]
)
)
await ctx.send(embed=embed, components=action_rows)
await message.add_reaction("")
message = await ctx.channel.fetch_message(message.id)
if (message.content != "" and
not isinstance(ctx.channel, discord.DMChannel)):
await message.clear_reactions()
async def add_movie(self, message, imdb_id, edit_message = True):
"""Add a movie to Plex server."""
if imdb_id is None:
if not edit_message:
await message.delete()
if imdb_id == "":
self.bot.log("Did not find what the user was searching for")
if edit_message:
await message.edit(
embed = None,
content = "Try searching for the IMDB id"
)
else:
await message.channel.send("Try searching for the IMDB id")
message_text = "Try searching for the IMDB id"
else:
self.bot.log("Trying to add movie "+str(imdb_id))
# Searches for the movie using the imdb id through Radarr
api_key = self.credentials["radarr_key"]
request_url = self.radarr_url+"movie/lookup/imdb?imdbId=tt"+imdb_id
request_url += "&apiKey="+api_key
response = requests.get(request_url)
# Makes the dict used for the post request
lookup_data = response.json()
post_data = {"qualityProfileId": 1,
"rootFolder_path" : self.movie_path,
"monitored" : True,
"addOptions": {"searchForMovie": True}}
post_data = {
"qualityProfileId": 1,
"rootFolderPath" : self.movie_path,
"monitored" : True,
"addOptions": {"searchForMovie": True}
}
for key in ["tmdbId","title","titleSlug","images","year"]:
post_data.update({key : lookup_data[key]})
# Makes the post request
response = requests.post(
url= self.radarr_url+"movie?apikey="+api_key,
url = self.radarr_url+"movie?apikey="+api_key,
json = post_data
)
# Deciphers the response
if response.status_code == 201:
success_message = "{} successfully added to Plex".format(
self.bot.log("Added "+post_data["title"]+" to Plex")
message_text = "{} successfully added to Plex".format(
post_data["title"]
)
if edit_message:
await message.edit(
embed = None,
content = success_message
)
else:
await message.channel.send(success_message)
self.bot.log("Added "+post_data["title"]+" to Plex")
elif response.status_code == 400:
fail_text = self.long_strings["Already on Plex"].format(
self.bot.log("The movie was already on plex")
message_text = self.long_strings["Already on Plex"].format(
post_data['title']
)
if edit_message:
await message.edit(embed = None, content = fail_text)
else:
await message.channel.send(fail_text)
else:
if edit_message:
await message.edit(
embed = None,
content = "Something went wrong"
)
else:
await message.channel.send("Something went wrong")
self.bot.log(str(response.status_code)+" "+response.reason)
message_text = "Something went wrong",
if edit_message:
await message.edit(
embed = None,
content = message_text,
components = []
)
else:
await message.channel.send(message_text)
async def request_show(self, ctx, show_name):
"""Request a show for the Plex server."""
@ -166,7 +184,7 @@ class Plex():
message_title = "**Is it any of these shows?**"
message_text = ""
imdb_names = []
imdb_ids = []
for i, show in enumerate(shows):
try:
@ -176,10 +194,10 @@ class Plex():
message_text += "\n"+str(i+1)+") "+show["title"]
except KeyError:
message_text += "Error"
imdb_names.append(show["title"])
imdb_ids.append(show.movieID)
self.bot.log(
f"Returning a list of {len(shows)} possible shows: {imdb_names}"
f"Returning a list of {len(shows)} possible shows: {imdb_ids}"
)
embed = discord.Embed(
@ -188,42 +206,69 @@ class Plex():
colour=0x00FF00
)
message = await ctx.send(embed=embed)
message_data = {"message_id":message.id,"imdb_names":imdb_names}
file_path = "gwendolyn/resources/plex/old_message"+str(ctx.channel.id)
with open(file_path,"w") as file_pointer:
json.dump(message_data, file_pointer)
buttons = []
if len(shows) == 1:
await message.add_reaction("✔️")
else:
for i in range(len(shows)):
await message.add_reaction(["1","2","3","4","5"][i])
await message.add_reaction("")
message = await ctx.channel.fetch_message(message.id)
if message.content != "":
if not isinstance(ctx.channel, discord.DMChannel):
await message.clear_reactions()
async def add_show(self, message, imdb_name):
"""Add the requested show to Plex."""
if imdb_name is None:
self.bot.log("Did not find what the user was searching for")
await message.edit(
embed = None,
content = "Try searching for the IMDB id"
buttons.append(create_button(
style=ButtonStyle.green,
label="",
custom_id=f"plex:show:{imdb_ids[0]}"
)
)
else:
self.bot.log("Trying to add show "+str(imdb_name))
for i in range(len(shows)):
buttons.append(
create_button(
style=ButtonStyle.blue,
label=str(i+1),
custom_id=f"plex:show:{imdb_ids[i]}"
)
)
buttons.append(create_button(
style=ButtonStyle.red,
label="X",
custom_id="plex:show:"
)
)
action_rows = []
for i in range(((len(buttons)-1)//5)+1):
action_rows.append(
create_actionrow(
*buttons[(i*5):(min(len(buttons),i*5+5))]
)
)
await ctx.send(embed=embed, components=action_rows)
async def add_show(self, message, imdb_id, edit_message = True):
"""Add the requested show to Plex."""
if imdb_id == "":
self.bot.log("Did not find what the user was searching for")
message_text = "Try searching for the IMDB id"
else:
self.bot.log("Trying to add show "+str(imdb_id))
# Finds the tvdb id
tvdb_api_url = "https://thetvdb.com/api/"
tvdb_method = "GetSeriesByRemoteID.php"
tvdb_request_url = f"{tvdb_api_url}{tvdb_method}"
tvdb_id = xmltodict.parse(
requests.get(
tvdb_request_url+f"?imdbid=tt{imdb_id}",
headers = {"ContentType" : "application/json"}
).text
)['Data']['Series']['seriesid']
# Finds the rest of the information using Sonarr
api_key = self.credentials["sonarr_key"]
request_url = self.sonarr_url+"series/lookup?term="
request_url += imdb_name.replace(" ","%20")
request_url += f"tvdb:{tvdb_id}"
request_url += "&apiKey="+api_key
response = requests.get(request_url)
# Makes the dict used for the post request
lookup_data = response.json()[0]
post_data = {
"ProfileId" : 1,
@ -234,29 +279,32 @@ class Plex():
for key in ["tvdbId","title","titleSlug","images","seasons"]:
post_data.update({key : lookup_data[key]})
# Makes the post request
response = requests.post(
url= self.sonarr_url+"series?apikey="+api_key,
json = post_data
)
# Deciphers the response
if response.status_code == 201:
await message.edit(
embed = None,
content = post_data["title"]+" successfully added to Plex"
)
self.bot.log("Added a "+post_data["title"]+" to Plex")
message_text = post_data["title"]+" successfully added to Plex"
elif response.status_code == 400:
text = self.long_strings["Already on Plex"].format(
message_text = self.long_strings["Already on Plex"].format(
post_data['title']
)
await message.edit(embed = None, content = text)
else:
await message.edit(
embed = None,
content = "Something went wrong"
)
self.bot.log(str(response.status_code)+" "+response.reason)
message_text = "Something went wrong"
if edit_message:
await message.edit(
embed = None,
content = message_text,
components = []
)
else:
await message.channel.send(message_text)
async def __generate_download_list(self, show_dm, show_movies, show_shows,
episodes):
@ -364,7 +412,9 @@ class Plex():
movie_list = requests.get(
self.radarr_url+"movie?apiKey="+self.credentials["radarr_key"]
).json()
print(self.radarr_url+"movie?apiKey="+self.credentials["radarr_key"])
print(
self.radarr_url+"movie?apiKey="+self.credentials["radarr_key"]
)
movie_queue = requests.get(
self.radarr_url+"queue?apiKey="+self.credentials["radarr_key"]
).json()