translate ver 0.1

discord.py req update to actual
This commit is contained in:
fixebr@gmail.com
2023-12-21 00:40:15 +03:00
parent 7583424cf2
commit 15fe90bb94
7 changed files with 115 additions and 115 deletions

View File

@@ -28,7 +28,7 @@ try:
PLEX_TOKEN = config.get(BOT_SECTION, 'plex_token') PLEX_TOKEN = config.get(BOT_SECTION, 'plex_token')
PLEX_BASE_URL = config.get(BOT_SECTION, 'plex_base_url') PLEX_BASE_URL = config.get(BOT_SECTION, 'plex_base_url')
except: except:
print("No Plex auth token details found") print("Сведения о токене аутентификации Plex не найдены.")
plex_token_configured = False plex_token_configured = False
# Get Plex config # Get Plex config
@@ -37,9 +37,9 @@ try:
PLEXPASS = config.get(BOT_SECTION, 'plex_pass') PLEXPASS = config.get(BOT_SECTION, 'plex_pass')
PLEX_SERVER_NAME = config.get(BOT_SECTION, 'plex_server_name') PLEX_SERVER_NAME = config.get(BOT_SECTION, 'plex_server_name')
except: except:
print("No Plex login info found") print("Информация для входа в Plex не найдена")
if not plex_token_configured: if not plex_token_configured:
print("Could not load plex config") print("Не удалось загрузить конфигурацию plex")
plex_configured = False plex_configured = False
# Get Plex roles config # Get Plex roles config
@@ -108,32 +108,32 @@ try:
JELLYFIN_EXTERNAL_URL = JELLYFIN_SERVER_URL JELLYFIN_EXTERNAL_URL = JELLYFIN_SERVER_URL
except: except:
JELLYFIN_EXTERNAL_URL = JELLYFIN_SERVER_URL JELLYFIN_EXTERNAL_URL = JELLYFIN_SERVER_URL
print("Could not get Jellyfin external url. Defaulting to server url.") print("Не удалось получить внешний URL-адрес Jellyfin. По умолчанию используется URL-адрес сервера.")
if USE_PLEX and plex_configured: if USE_PLEX and plex_configured:
try: try:
print("Connecting to Plex......") print("Подключение к Plex......")
if plex_token_configured and PLEX_TOKEN and PLEX_BASE_URL: if plex_token_configured and PLEX_TOKEN and PLEX_BASE_URL:
print("Using Plex auth token") print("Использование токена аутентификации Plex")
plex = PlexServer(PLEX_BASE_URL, PLEX_TOKEN) plex = PlexServer(PLEX_BASE_URL, PLEX_TOKEN)
else: else:
print("Using Plex login info") print("Использование данных для входа в Plex")
account = MyPlexAccount(PLEXUSER, PLEXPASS) account = MyPlexAccount(PLEXUSER, PLEXPASS)
plex = account.resource(PLEX_SERVER_NAME).connect() # returns a PlexServer instance plex = account.resource(PLEX_SERVER_NAME).connect() # returns a PlexServer instance
print('Logged into plex!') print('Зашёл в Plex!')
except Exception as e: except Exception as e:
# probably rate limited. # probably rate limited.
print('Error with plex login. Please check Plex authentication details. If you have restarted the bot multiple times recently, this is most likely due to being ratelimited on the Plex API. Try again in 10 minutes.') print('Ошибка при входе в plex. Пожалуйста, проверьте данные аутентификации Plex. Если вы в последнее время перезапускали бота несколько раз, скорее всего, это связано с ограничением скорости в Plex API. Повторите попытку через 10 минут.')
print(f'Error: {e}') print(f'Error: {e}')
else: else:
print(f"Plex {'disabled' if not USE_PLEX else 'not configured'}. Skipping Plex login.") print(f"Plex {'выключен' if not USE_PLEX else 'не настроен'}. Пропуск входа в Plex.")
class app(commands.Cog): class app(commands.Cog):
# App command groups # App command groups
plex_commands = app_commands.Group(name="plex", description="Membarr Plex commands") plex_commands = app_commands.Group(name="plex", description="Команды Membarr Plex")
jellyfin_commands = app_commands.Group(name="jellyfin", description="Membarr Jellyfin commands") jellyfin_commands = app_commands.Group(name="jellyfin", description="Команды Membarr Jellyfin")
membarr_commands = app_commands.Group(name="membarr", description="Membarr general commands") membarr_commands = app_commands.Group(name="membarr", description="Membarr общие команды")
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@@ -150,14 +150,14 @@ class app(commands.Cog):
# TODO: Make these debug statements work. roles are currently empty arrays if no roles assigned. # TODO: Make these debug statements work. roles are currently empty arrays if no roles assigned.
if plex_roles is None: if plex_roles is None:
print('Configure Plex roles to enable auto invite to Plex after a role is assigned.') print('Настройте роли Plex, чтобы включить автоматическое приглашение в Plex после назначения роли.')
if jellyfin_roles is None: if jellyfin_roles is None:
print('Configure Jellyfin roles to enable auto invite to Jellyfin after a role is assigned.') print('Настройте роли Jellyfin, чтобы включить автоматическое приглашение в Jellyfin после назначения роли.')
async def getemail(self, after): async def getemail(self, after):
email = None email = None
await embedinfo(after,'Welcome To '+ PLEX_SERVER_NAME +'. Please reply with your email to be added to the Plex server!') await embedinfo(after,'Добро пожаловать в '+ PLEX_SERVER_NAME +'. Пожалуйста, ответьте на свой адрес электронной почты, который будет добавлен на сервер Plex!')
await embedinfo(after,'If you do not respond within 24 hours, the request will be cancelled, and the server admin will need to add you manually.') await embedinfo(after,'Если вы не ответите в течение 24 часов, запрос будет отменен, и администратору сервера придется добавить вас вручную.')
while(email == None): while(email == None):
def check(m): def check(m):
return m.author == after and not m.guild return m.author == after and not m.guild
@@ -167,18 +167,18 @@ class app(commands.Cog):
return str(email.content) return str(email.content)
else: else:
email = None email = None
message = "The email you provided is invalid, please respond only with the email you used to sign up for Plex." message = "Указанный вами адрес электронной почты недействителен. В ответе укажите адрес электронной почты, который вы использовали при регистрации в Plex."
await embederror(after, message) await embederror(after, message)
continue continue
except asyncio.TimeoutError: except asyncio.TimeoutError:
message = "Timed out. Please contact the server admin directly." message = "Время вышло. Пожалуйста, свяжитесь напрямую с администратором сервера."
await embederror(after, message) await embederror(after, message)
return None return None
async def getusername(self, after): async def getusername(self, after):
username = None username = None
await embedinfo(after, f"Welcome To Jellyfin! Please reply with your username to be added to the Jellyfin server!") await embedinfo(after, f"Добро пожаловать в Jellyfin! Пожалуйста, укажите в ответе свое имя пользователя, которое будет добавлено на сервер Jellyfin!")
await embedinfo(after, f"If you do not respond within 24 hours, the request will be cancelled, and the server admin will need to add you manually.") await embedinfo(after, f"Если вы не ответите в течение 24 часов, запрос будет отменен, и администратору сервера придется добавить вас вручную.")
while (username is None): while (username is None):
def check(m): def check(m):
return m.author == after and not m.guild return m.author == after and not m.guild
@@ -188,16 +188,16 @@ class app(commands.Cog):
return str(username.content) return str(username.content)
else: else:
username = None username = None
message = "This username is already choosen. Please select another username." message = "Это имя пользователя уже занято. Пожалуйста, выберите другое имя пользователя."
await embederror(after, message) await embederror(after, message)
continue continue
except asyncio.TimeoutError: except asyncio.TimeoutError:
message = "Timed out. Please contact the server admin directly." message = "Время вышло. Пожалуйста, свяжитесь напрямую с администратором сервера."
print("Jellyfin user prompt timed out") print("Время ожидания запроса пользователя Jellyfin истекло")
await embederror(after, message) await embederror(after, message)
return None return None
except Exception as e: except Exception as e:
await embederror(after, "Something went wrong. Please try again with another username.") await embederror(after, "Что-то пошло не так. Пожалуйста, попробуйте еще раз с другим именем пользователя.")
print (e) print (e)
username = None username = None
@@ -205,48 +205,48 @@ class app(commands.Cog):
async def addtoplex(self, email, response): async def addtoplex(self, email, response):
if(plexhelper.verifyemail(email)): if(plexhelper.verifyemail(email)):
if plexhelper.plexadd(plex,email,Plex_LIBS): if plexhelper.plexadd(plex,email,Plex_LIBS):
await embedinfo(response, 'This email address has been added to plex') await embedinfo(response, 'Этот адрес электронной почты был добавлен в plex')
return True return True
else: else:
await embederror(response, 'There was an error adding this email address. Check logs.') await embederror(response, 'Произошла ошибка при добавлении этого адреса электронной почты. Проверьте журналы.')
return False return False
else: else:
await embederror(response, 'Invalid email.') await embederror(response, 'Неверный адрес электронной почты.')
return False return False
async def removefromplex(self, email, response): async def removefromplex(self, email, response):
if(plexhelper.verifyemail(email)): if(plexhelper.verifyemail(email)):
if plexhelper.plexremove(plex,email): if plexhelper.plexremove(plex,email):
await embedinfo(response, 'This email address has been removed from plex.') await embedinfo(response, 'Этот адрес электронной почты был удален из plex.')
return True return True
else: else:
await embederror(response, 'There was an error removing this email address. Check logs.') await embederror(response, 'Произошла ошибка при удалении этого адреса электронной почты. Проверьте журналы.')
return False return False
else: else:
await embederror(response, 'Invalid email.') await embederror(response, 'Неверный адрес электронной почты.')
return False return False
async def addtojellyfin(self, username, password, response): async def addtojellyfin(self, username, password, response):
if not jelly.verify_username(JELLYFIN_SERVER_URL, JELLYFIN_API_KEY, username): if not jelly.verify_username(JELLYFIN_SERVER_URL, JELLYFIN_API_KEY, username):
await embederror(response, f'An account with username {username} already exists.') await embederror(response, f'Учетная запись с именем пользователя {username} уже существует.')
return False return False
if jelly.add_user(JELLYFIN_SERVER_URL, JELLYFIN_API_KEY, username, password, jellyfin_libs): if jelly.add_user(JELLYFIN_SERVER_URL, JELLYFIN_API_KEY, username, password, jellyfin_libs):
return True return True
else: else:
await embederror(response, 'There was an error adding this user to Jellyfin. Check logs for more info.') await embederror(response, 'Произошла ошибка при добавлении этого пользователя в Jellyfin. Проверьте журналы для получения дополнительной информации.')
return False return False
async def removefromjellyfin(self, username, response): async def removefromjellyfin(self, username, response):
if jelly.verify_username(JELLYFIN_SERVER_URL, JELLYFIN_API_KEY, username): if jelly.verify_username(JELLYFIN_SERVER_URL, JELLYFIN_API_KEY, username):
await embederror(response, f'Could not find account with username {username}.') await embederror(response, f'Не удалось найти учетную запись с именем пользователя {username}.')
return return
if jelly.remove_user(JELLYFIN_SERVER_URL, JELLYFIN_API_KEY, username): if jelly.remove_user(JELLYFIN_SERVER_URL, JELLYFIN_API_KEY, username):
await embedinfo(response, f'Successfully removed user {username} from Jellyfin.') await embedinfo(response, f'Пользователь {username} успешно удален из Jellyfin.')
return True return True
else: else:
await embederror(response, f'There was an error removing this user from Jellyfin. Check logs for more info.') await embederror(response, f'Произошла ошибка при удалении этого пользователя из Jellyfin. Проверьте журналы для получения дополнительной информации.')
return False return False
@commands.Cog.listener() @commands.Cog.listener()
@@ -270,13 +270,13 @@ class app(commands.Cog):
if role is not None and (role in after.roles and role not in before.roles): if role is not None and (role in after.roles and role not in before.roles):
email = await self.getemail(after) email = await self.getemail(after)
if email is not None: if email is not None:
await embedinfo(after, "Got it we will be adding your email to plex shortly!") await embedinfo(after, "Понятно, в ближайшее время мы добавим ваш адрес электронной почты в plex!")
if plexhelper.plexadd(plex,email,Plex_LIBS): if plexhelper.plexadd(plex,email,Plex_LIBS):
db.save_user_email(str(after.id), email) db.save_user_email(str(after.id), email)
await asyncio.sleep(5) await asyncio.sleep(5)
await embedinfo(after, 'You have Been Added To Plex! Login to plex and accept the invite!') await embedinfo(after, 'Вас добавили в Plex! Войдите в plex и примите приглашение!')
else: else:
await embedinfo(after, 'There was an error adding this email address. Message Server Admin.') await embedinfo(after, 'Произошла ошибка при добавлении этого адреса электронной почты. Напишите администраторам сервера.')
plex_processed = True plex_processed = True
break break
@@ -288,14 +288,14 @@ class app(commands.Cog):
plexhelper.plexremove(plex,email) plexhelper.plexremove(plex,email)
deleted = db.remove_email(user_id) deleted = db.remove_email(user_id)
if deleted: if deleted:
print("Removed Plex email {} from db".format(after.name)) print("Удален адрес электронной почты Plex {} из базы данных.".format(after.name))
#await secure.send(plexname + ' ' + after.mention + ' was removed from plex') #await secure.send(plexname + ' ' + after.mention + ' was removed from plex')
else: else:
print("Cannot remove Plex from this user.") print("Невозможно удалить Plex у этого пользователя.")
await embedinfo(after, "You have been removed from Plex") await embedinfo(after, "Вас удалили из Plex")
except Exception as e: except Exception as e:
print(e) print(e)
print("{} Cannot remove this user from plex.".format(email)) print("{} Невозможно удалить этого пользователя из plex.".format(email))
plex_processed = True plex_processed = True
break break
if plex_processed: if plex_processed:
@@ -311,39 +311,39 @@ class app(commands.Cog):
# Jellyfin role was added # Jellyfin role was added
if role is not None and (role in after.roles and role not in before.roles): if role is not None and (role in after.roles and role not in before.roles):
print("Jellyfin role added") print("Добавлена ​​роль Jellyfin")
username = await self.getusername(after) username = await self.getusername(after)
print("Username retrieved from user") print("Имя пользователя получено от пользователя")
if username is not None: if username is not None:
await embedinfo(after, "Got it we will be creating your Jellyfin account shortly!") await embedinfo(after, "Поодождите, в ближайшее время мы создадим вашу учетную запись Jellyfin!")
password = jelly.generate_password(16) password = jelly.generate_password(16)
if jelly.add_user(JELLYFIN_SERVER_URL, JELLYFIN_API_KEY, username, password, jellyfin_libs): if jelly.add_user(JELLYFIN_SERVER_URL, JELLYFIN_API_KEY, username, password, jellyfin_libs):
db.save_user_jellyfin(str(after.id), username) db.save_user_jellyfin(str(after.id), username)
await asyncio.sleep(5) await asyncio.sleep(5)
await embedcustom(after, "You have been added to Jellyfin!", {'Username': username, 'Password': f"||{password}||"}) await embedcustom(after, "Вы добавлены в Jellyfin!", {'Username': username, 'Password': f"||{password}||"})
await embedinfo(after, f"Go to {JELLYFIN_EXTERNAL_URL} to log in!") await embedinfo(after, f"Перейдите по адресу {JELLYFIN_EXTERNAL_URL}, чтобы войти!")
else: else:
await embedinfo(after, 'There was an error adding this user to Jellyfin. Message Server Admin.') await embedinfo(after, 'Произошла ошибка при добавлении этого пользователя в Jellyfin. Напишите администраторам сервера.')
jellyfin_processed = True jellyfin_processed = True
break break
# Jellyfin role was removed # Jellyfin role was removed
elif role is not None and (role not in after.roles and role in before.roles): elif role is not None and (role not in after.roles and role in before.roles):
print("Jellyfin role removed") print("Роль Jellyfin удалена")
try: try:
user_id = after.id user_id = after.id
username = db.get_jellyfin_username(user_id) username = db.get_jellyfin_username(user_id)
jelly.remove_user(JELLYFIN_SERVER_URL, JELLYFIN_API_KEY, username) jelly.remove_user(JELLYFIN_SERVER_URL, JELLYFIN_API_KEY, username)
deleted = db.remove_jellyfin(user_id) deleted = db.remove_jellyfin(user_id)
if deleted: if deleted:
print("Removed Jellyfin from {}".format(after.name)) print("Удален Jellyfin из {}".format(after.name))
#await secure.send(plexname + ' ' + after.mention + ' was removed from plex') #await secure.send(plexname + ' ' + after.mention + ' was removed from plex')
else: else:
print("Cannot remove Jellyfin from this user") print("Невозможно удалить Jellyfin у этого пользователя.")
await embedinfo(after, "You have been removed from Jellyfin") await embedinfo(after, "Вас удалили из Jellyfin")
except Exception as e: except Exception as e:
print(e) print(e)
print("{} Cannot remove this user from Jellyfin.".format(username)) print("{} Невозможно удалить этого пользователя из Jellyfin.".format(username))
jellyfin_processed = True jellyfin_processed = True
break break
if jellyfin_processed: if jellyfin_processed:
@@ -361,53 +361,53 @@ class app(commands.Cog):
deleted = db.delete_user(member.id) deleted = db.delete_user(member.id)
if deleted: if deleted:
print("Removed {} from db because user left discord server.".format(email)) print("Удален {} из базы данных, поскольку пользователь покинул сервер Discord.".format(email))
@app_commands.checks.has_permissions(administrator=True) @app_commands.checks.has_permissions(administrator=True)
@plex_commands.command(name="invite", description="Invite a user to Plex") @plex_commands.command(name="invite", description="Пригласить пользователя в Plex")
async def plexinvite(self, interaction: discord.Interaction, email: str): async def plexinvite(self, interaction: discord.Interaction, email: str):
await self.addtoplex(email, interaction.response) await self.addtoplex(email, interaction.response)
@app_commands.checks.has_permissions(administrator=True) @app_commands.checks.has_permissions(administrator=True)
@plex_commands.command(name="remove", description="Remove a user from Plex") @plex_commands.command(name="remove", description="Удаление пользователя из Plex")
async def plexremove(self, interaction: discord.Interaction, email: str): async def plexremove(self, interaction: discord.Interaction, email: str):
await self.removefromplex(email, interaction.response) await self.removefromplex(email, interaction.response)
@app_commands.checks.has_permissions(administrator=True) @app_commands.checks.has_permissions(administrator=True)
@jellyfin_commands.command(name="invite", description="Invite a user to Jellyfin") @jellyfin_commands.command(name="invite", description="Пригласить пользователя в Jellyfin")
async def jellyfininvite(self, interaction: discord.Interaction, username: str): async def jellyfininvite(self, interaction: discord.Interaction, username: str):
password = jelly.generate_password(16) password = jelly.generate_password(16)
if await self.addtojellyfin(username, password, interaction.response): if await self.addtojellyfin(username, password, interaction.response):
await embedcustom(interaction.response, "Jellyfin user created!", {'Username': username, 'Password': f"||{password}||"}) await embedcustom(interaction.response, "Пользователь Jellyfin создан!", {'Username': username, 'Password': f"||{password}||"})
@app_commands.checks.has_permissions(administrator=True) @app_commands.checks.has_permissions(administrator=True)
@jellyfin_commands.command(name="remove", description="Remove a user from Jellyfin") @jellyfin_commands.command(name="remove", description="Удаление пользователя из Jellyfin")
async def jellyfinremove(self, interaction: discord.Interaction, username: str): async def jellyfinremove(self, interaction: discord.Interaction, username: str):
await self.removefromjellyfin(username, interaction.response) await self.removefromjellyfin(username, interaction.response)
@app_commands.checks.has_permissions(administrator=True) @app_commands.checks.has_permissions(administrator=True)
@membarr_commands.command(name="dbadd", description="Add a user to the Membarr database") @membarr_commands.command(name="dbadd", description="Добавьте пользователя в базу данных Membarr")
async def dbadd(self, interaction: discord.Interaction, member: discord.Member, email: str = "", jellyfin_username: str = ""): async def dbadd(self, interaction: discord.Interaction, member: discord.Member, email: str = "", jellyfin_username: str = ""):
email = email.strip() email = email.strip()
jellyfin_username = jellyfin_username.strip() jellyfin_username = jellyfin_username.strip()
# Check email if provided # Check email if provided
if email and not plexhelper.verifyemail(email): if email and not plexhelper.verifyemail(email):
await embederror(interaction.response, "Invalid email.") await embederror(interaction.response, "Неверный адрес электронной почты.")
return return
try: try:
db.save_user_all(str(member.id), email, jellyfin_username) db.save_user_all(str(member.id), email, jellyfin_username)
await embedinfo(interaction.response,'User was added to the database.') await embedinfo(interaction.response,'Пользователь добавлен в базу данных.')
except Exception as e: except Exception as e:
await embedinfo(interaction.response, 'There was an error adding this user to database. Check Membarr logs for more info') await embedinfo(interaction.response, 'Произошла ошибка при добавлении этого пользователя в базу данных. Проверьте журналы Membarr для получения дополнительной информации.')
print(e) print(e)
@app_commands.checks.has_permissions(administrator=True) @app_commands.checks.has_permissions(administrator=True)
@membarr_commands.command(name="dbls", description="View Membarr database") @membarr_commands.command(name="dbls", description="Посмотреть базу данных Memarr")
async def dbls(self, interaction: discord.Interaction): async def dbls(self, interaction: discord.Interaction):
embed = discord.Embed(title='Membarr Database.') embed = discord.Embed(title='База данных Memarr.')
all = db.read_all() all = db.read_all()
table = texttable.Texttable() table = texttable.Texttable()
table.set_cols_dtype(["t", "t", "t", "t"]) table.set_cols_dtype(["t", "t", "t", "t"])
@@ -432,15 +432,15 @@ class app(commands.Cog):
f = open("db.txt", "w") f = open("db.txt", "w")
f.write(table.draw()) f.write(table.draw())
f.close() f.close()
await interaction.response.send_message("Database too large! Total: {total}".format(total = total),file=discord.File('db.txt'), ephemeral=True) await interaction.response.send_message("База данных слишком велика! Итого: {total}".format(total = total),file=discord.File('db.txt'), ephemeral=True)
else: else:
await interaction.response.send_message(embed = embed, ephemeral=True) await interaction.response.send_message(embed = embed, ephemeral=True)
@app_commands.checks.has_permissions(administrator=True) @app_commands.checks.has_permissions(administrator=True)
@membarr_commands.command(name="dbrm", description="Remove user from Membarr database") @membarr_commands.command(name="dbrm", description="Удалить пользователя из базы данных Membarr")
async def dbrm(self, interaction: discord.Interaction, position: int): async def dbrm(self, interaction: discord.Interaction, position: int):
embed = discord.Embed(title='Membarr Database.') embed = discord.Embed(title='База данных Memarr.')
all = db.read_all() all = db.read_all()
for index, peoples in enumerate(all): for index, peoples in enumerate(all):
index = index + 1 index = index + 1
@@ -461,10 +461,10 @@ class app(commands.Cog):
username = discord_user.name username = discord_user.name
deleted = db.delete_user(id) deleted = db.delete_user(id)
if deleted: if deleted:
print("Removed {} from db".format(username)) print("{} удален из базы данных.".format(username))
await embedinfo(interaction.response,"Removed {} from db".format(username)) await embedinfo(interaction.response,"{} удален из базы данных.".format(username))
else: else:
await embederror(interaction.response,"Cannot remove this user from db.") await embederror(interaction.response,"Невозможно удалить этого пользователя из базы данных.")
except Exception as e: except Exception as e:
print(e) print(e)

View File

@@ -64,7 +64,7 @@ try:
PLEX_TOKEN = config.get(BOT_SECTION, 'plex_token') PLEX_TOKEN = config.get(BOT_SECTION, 'plex_token')
PLEX_BASE_URL = config.get(BOT_SECTION, 'plex_base_url') PLEX_BASE_URL = config.get(BOT_SECTION, 'plex_base_url')
except: except:
print("No Plex auth token details found") print("Сведения о токене аутентификации Plex не найдены.")
plex_token_configured = False plex_token_configured = False
# Get Plex config # Get Plex config
@@ -73,16 +73,16 @@ try:
PLEXUSER = config.get(BOT_SECTION, 'plex_user') PLEXUSER = config.get(BOT_SECTION, 'plex_user')
PLEXPASS = config.get(BOT_SECTION, 'plex_pass') PLEXPASS = config.get(BOT_SECTION, 'plex_pass')
except: except:
print("No Plex login info found") print("Информация для входа в Plex не найдена")
if not plex_token_configured: if not plex_token_configured:
print("Could not load plex config") print("Не удалось загрузить конфигурацию plex")
plex_configured = False plex_configured = False
# Get Plex roles config # Get Plex roles config
try: try:
plex_roles = config.get(BOT_SECTION, 'plex_roles') plex_roles = config.get(BOT_SECTION, 'plex_roles')
except: except:
print("Could not get Plex roles config") print("Не удалось получить конфигурацию ролей Plex.")
plex_roles = None plex_roles = None
if plex_roles: if plex_roles:
plex_roles = list(plex_roles.split(',')) plex_roles = list(plex_roles.split(','))
@@ -93,7 +93,7 @@ else:
try: try:
Plex_LIBS = config.get(BOT_SECTION, 'plex_libs') Plex_LIBS = config.get(BOT_SECTION, 'plex_libs')
except: except:
print("Could not get Plex libs config. Defaulting to all libraries.") print("Не удалось получить конфигурацию Plex libs. По умолчанию для всех библиотек.")
Plex_LIBS = None Plex_LIBS = None
if Plex_LIBS is None: if Plex_LIBS is None:
Plex_LIBS = ["all"] Plex_LIBS = ["all"]
@@ -105,7 +105,7 @@ try:
JELLYFIN_SERVER_URL = config.get(BOT_SECTION, 'jellyfin_server_url') JELLYFIN_SERVER_URL = config.get(BOT_SECTION, 'jellyfin_server_url')
JELLYFIN_API_KEY = config.get(BOT_SECTION, "jellyfin_api_key") JELLYFIN_API_KEY = config.get(BOT_SECTION, "jellyfin_api_key")
except: except:
print("Could not load Jellyfin config") print("Не удалось загрузить конфигурацию Jellyfin.")
jellyfin_configured = False jellyfin_configured = False
try: try:
@@ -114,13 +114,13 @@ try:
JELLYFIN_EXTERNAL_URL = JELLYFIN_SERVER_URL JELLYFIN_EXTERNAL_URL = JELLYFIN_SERVER_URL
except: except:
JELLYFIN_EXTERNAL_URL = JELLYFIN_SERVER_URL JELLYFIN_EXTERNAL_URL = JELLYFIN_SERVER_URL
print("Could not get Jellyfin external url. Defaulting to server url.") print("Не удалось получить внешний URL-адрес Jellyfin. По умолчанию используется URL-адрес сервера.")
# Get Jellyfin roles config # Get Jellyfin roles config
try: try:
jellyfin_roles = config.get(BOT_SECTION, 'jellyfin_roles') jellyfin_roles = config.get(BOT_SECTION, 'jellyfin_roles')
except: except:
print("Could not get Jellyfin roles config") print("Не удалось получить конфигурацию ролей Jellyfin.")
jellyfin_roles = None jellyfin_roles = None
if jellyfin_roles: if jellyfin_roles:
jellyfin_roles = list(jellyfin_roles.split(',')) jellyfin_roles = list(jellyfin_roles.split(','))
@@ -131,7 +131,7 @@ else:
try: try:
jellyfin_libs = config.get(BOT_SECTION, 'jellyfin_libs') jellyfin_libs = config.get(BOT_SECTION, 'jellyfin_libs')
except: except:
print("Could not get Jellyfin libs config. Defaulting to all libraries.") print("Не удалось получить конфигурацию Jellyfin libs. По умолчанию для всех библиотек.")
jellyfin_libs = None jellyfin_libs = None
if jellyfin_libs is None: if jellyfin_libs is None:
jellyfin_libs = ["all"] jellyfin_libs = ["all"]
@@ -143,14 +143,14 @@ try:
USE_JELLYFIN = config.get(BOT_SECTION, 'jellyfin_enabled') USE_JELLYFIN = config.get(BOT_SECTION, 'jellyfin_enabled')
USE_JELLYFIN = USE_JELLYFIN.lower() == "true" USE_JELLYFIN = USE_JELLYFIN.lower() == "true"
except: except:
print("Could not get Jellyfin enable config. Defaulting to False") print("Не удалось получить конфигурацию включения Jellyfin. По умолчанию установлено значение False")
USE_JELLYFIN = False USE_JELLYFIN = False
try: try:
USE_PLEX = config.get(BOT_SECTION, "plex_enabled") USE_PLEX = config.get(BOT_SECTION, "plex_enabled")
USE_PLEX = USE_PLEX.lower() == "true" USE_PLEX = USE_PLEX.lower() == "true"
except: except:
print("Could not get Plex enable config. Defaulting to False") print("Не удалось получить конфигурацию включения Plex. По умолчанию установлено значение False")
USE_PLEX = False USE_PLEX = False
def get_config(): def get_config():
@@ -162,7 +162,7 @@ def get_config():
return config return config
except Exception as e: except Exception as e:
print(e) print(e)
print('error in reading config') print('ошибка чтения конфига')
return None return None
@@ -175,7 +175,7 @@ def change_config(key, value):
config.read(CONFIG_PATH) config.read(CONFIG_PATH)
except Exception as e: except Exception as e:
print(e) print(e)
print("Cannot Read config.") print("Невозможно прочитать конфигурацию.")
try: try:
config.set(BOT_SECTION, key, str(value)) config.set(BOT_SECTION, key, str(value))
@@ -188,4 +188,4 @@ def change_config(key, value):
config.write(configfile) config.write(configfile)
except Exception as e: except Exception as e:
print(e) print(e)
print("Cannot write to config.") print("Не могу записать в конфиг.")

View File

@@ -50,17 +50,17 @@ def save_user_email(username, email):
VALUES('{username}', '{email}') VALUES('{username}', '{email}')
""") """)
conn.commit() conn.commit()
print("User added to db.") print("Пользователь добавлен в базу.")
else: else:
return "Username and email cannot be empty" return "Имя пользователя и адрес электронной почты не могут быть пустыми."
def save_user(username): def save_user(username):
if username: if username:
conn.execute("INSERT INTO clients (discord_username) VALUES ('"+ username +"')") conn.execute("INSERT INTO clients (discord_username) VALUES ('"+ username +"')")
conn.commit() conn.commit()
print("User added to db.") print("Пользователь добавлен в БД.")
else: else:
return "Username cannot be empty" return "Имя пользователя не может быть пустым"
def save_user_jellyfin(username, jellyfin_username): def save_user_jellyfin(username, jellyfin_username):
if username and jellyfin_username: if username and jellyfin_username:
@@ -69,9 +69,9 @@ def save_user_jellyfin(username, jellyfin_username):
VALUES('{username}', '{jellyfin_username}') VALUES('{username}', '{jellyfin_username}')
""") """)
conn.commit() conn.commit()
print("User added to db.") print("Пользователь добавлен в БД.")
else: else:
return "Discord and Jellyfin usernames cannot be empty" return "Имена пользователей Discord и Jellyfin не могут быть пустыми."
def save_user_all(username, email, jellyfin_username): def save_user_all(username, email, jellyfin_username):
if username and email and jellyfin_username: if username and email and jellyfin_username:
@@ -80,7 +80,7 @@ def save_user_all(username, email, jellyfin_username):
VALUES('{username}', '{email}', '{jellyfin_username}') VALUES('{username}', '{email}', '{jellyfin_username}')
""") """)
conn.commit() conn.commit()
print("User added to db.") print("Пользователь добавлен в БД.")
elif username and email: elif username and email:
save_user_email(username, email) save_user_email(username, email)
elif username and jellyfin_username: elif username and jellyfin_username:
@@ -88,7 +88,7 @@ def save_user_all(username, email, jellyfin_username):
elif username: elif username:
save_user(username) save_user(username)
else: else:
return "Discord username must all be provided" return "Необходимо указать имя пользователя Discord."
def get_useremail(username): def get_useremail(username):
if username: if username:
@@ -99,11 +99,11 @@ def get_useremail(username):
if email: if email:
return email return email
else: else:
return "No email found" return "Электронная почта не найдена"
except: except:
return "error in fetching from db" return "ошибка при извлечении из БД"
else: else:
return "username cannot be empty" return "имя пользователя не может быть пустым"
def get_jellyfin_username(username): def get_jellyfin_username(username):
""" """
@@ -121,11 +121,11 @@ def get_jellyfin_username(username):
if jellyfin_username: if jellyfin_username:
return jellyfin_username return jellyfin_username
else: else:
return "No users found" return "Пользователи не найдены"
except: except:
return "error in fetching from db" return "ошибка при извлечении из БД"
else: else:
return "username cannot be empty" return "имя пользователя не может быть пустым"
def remove_email(username): def remove_email(username):
""" """
@@ -134,10 +134,10 @@ def remove_email(username):
if username: if username:
conn.execute(f"UPDATE clients SET email = null WHERE discord_username = '{username}'") conn.execute(f"UPDATE clients SET email = null WHERE discord_username = '{username}'")
conn.commit() conn.commit()
print(f"Email removed from user {username} in database") print(f"Адрес электронной почты удален от пользователя {username} в базе данных.")
return True return True
else: else:
print(f"Username cannot be empty.") print(f"Имя пользователя не может быть пустым.")
return False return False
def remove_jellyfin(username): def remove_jellyfin(username):
@@ -147,10 +147,10 @@ def remove_jellyfin(username):
if username: if username:
conn.execute(f"UPDATE clients SET jellyfin_username = null WHERE discord_username = '{username}'") conn.execute(f"UPDATE clients SET jellyfin_username = null WHERE discord_username = '{username}'")
conn.commit() conn.commit()
print(f"Jellyfin username removed from user {username} in database") print(f"Имя пользователя Jellyfin удалено из пользователя {username} в базе данных.")
return True return True
else: else:
print(f"Username cannot be empty.") print(f"Имя пользователя не может быть пустым.")
return False return False
@@ -163,7 +163,7 @@ def delete_user(username):
except: except:
return False return False
else: else:
return "username cannot be empty" return "Имя пользователя не может быть пустым"
def read_all(): def read_all():
cur = conn.cursor() cur = conn.cursor()

View File

@@ -16,7 +16,7 @@ def add_user(jellyfin_url, jellyfin_api_key, username, password, jellyfin_libs):
userId = response.json()["Id"] userId = response.json()["Id"]
if response.status_code != 200: if response.status_code != 200:
print(f"Error creating new Jellyfin user: {response.text}") print(f"Ошибка создания нового пользователя Jellyfin: {response.text}")
return False return False
# Grant access to User # Grant access to User
@@ -35,7 +35,7 @@ def add_user(jellyfin_url, jellyfin_api_key, username, password, jellyfin_libs):
enabled_folders.append(server_lib['ItemId']) enabled_folders.append(server_lib['ItemId'])
found = True found = True
if not found: if not found:
print(f"Couldn't find Jellyfin Library: {lib}") print(f"Не удалось найти библиотеку Jellyfin: {lib}")
payload = { payload = {
"IsAdministrator": False, "IsAdministrator": False,
@@ -84,7 +84,7 @@ def add_user(jellyfin_url, jellyfin_api_key, username, password, jellyfin_libs):
if response.status_code == 200 or response.status_code == 204: if response.status_code == 200 or response.status_code == 204:
return True return True
else: else:
print(f"Error setting user permissions: {response.text}") print(f"Ошибка установки прав пользователя: {response.text}")
except Exception as e: except Exception as e:
print(e) print(e)
@@ -119,7 +119,7 @@ def remove_user(jellyfin_url, jellyfin_api_key, jellyfin_username):
if userId is None: if userId is None:
# User not found # User not found
print(f"Error removing user {jellyfin_username} from Jellyfin: Could not find user.") print(f"Ошибка удаления пользователя {jellyfin_username} из Jellyfin: не удалось найти пользователя.")
return False return False
# Delete User # Delete User
@@ -131,7 +131,7 @@ def remove_user(jellyfin_url, jellyfin_api_key, jellyfin_username):
if response.status_code == 204 or response.status_code == 200: if response.status_code == 204 or response.status_code == 200:
return True return True
else: else:
print(f"Error deleting Jellyfin user: {response.text}") print(f"Ошибка удаления пользователя Jellyfin: {response.text}")
except Exception as e: except Exception as e:
print(e) print(e)
return False return False
@@ -147,7 +147,7 @@ def get_users(jellyfin_url, jellyfin_api_key):
def generate_password(length, lower=True, upper=True, numbers=True, symbols=True): def generate_password(length, lower=True, upper=True, numbers=True, symbols=True):
character_list = [] character_list = []
if not (lower or upper or numbers or symbols): if not (lower or upper or numbers or symbols):
raise ValueError("At least one character type must be provided") raise ValueError("Должен быть указан хотя бы один тип символов.")
if lower: if lower:
character_list += string.ascii_lowercase character_list += string.ascii_lowercase

View File

@@ -8,7 +8,7 @@ def plexadd(plex, plexname, Plex_LIBS):
plex.myPlexAccount().inviteFriend(user=plexname, server=plex, sections=Plex_LIBS, allowSync=False, plex.myPlexAccount().inviteFriend(user=plexname, server=plex, sections=Plex_LIBS, allowSync=False,
allowCameraUpload=False, allowChannels=False, filterMovies=None, allowCameraUpload=False, allowChannels=False, filterMovies=None,
filterTelevision=None, filterMusic=None) filterTelevision=None, filterMusic=None)
print(plexname +' has been added to plex') print(plexname +' добавлен в plex')
return True return True
except Exception as e: except Exception as e:
print(e) print(e)
@@ -18,7 +18,7 @@ def plexadd(plex, plexname, Plex_LIBS):
def plexremove(plex, plexname): def plexremove(plex, plexname):
try: try:
plex.myPlexAccount().removeFriend(user=plexname) plex.myPlexAccount().removeFriend(user=plexname)
print(plexname +' has been removed from plex') print(plexname +' удалён из plex')
return True return True
except Exception as e: except Exception as e:
print(e) print(e)

View File

@@ -3,4 +3,4 @@ PlexAPI==4.13.0
texttable texttable
python-dotenv python-dotenv
requests requests
discord.py==2.0.1 discord.py

2
run.py
View File

@@ -37,7 +37,7 @@ class Bot(commands.Bot):
await self.tree.sync(guild=guild) await self.tree.sync(guild=guild)
async def on_guild_join(self, guild): async def on_guild_join(self, guild):
print(f"Вступил в гильдию {guild.name}") print(f"Зашёл на сервер {guild.name}")
print(f"Синхронизация команд с {guild.name}") print(f"Синхронизация команд с {guild.name}")
self.tree.copy_global_to(guild=guild) self.tree.copy_global_to(guild=guild)
await self.tree.sync(guild=guild) await self.tree.sync(guild=guild)