Changed the way exceptions are handled

This commit is contained in:
Profitroll 2023-02-17 16:45:51 +01:00
parent 663a7b0db8
commit 07203a9db9
4 changed files with 46 additions and 3 deletions

16
classes/exceptions.py Normal file
View File

@ -0,0 +1,16 @@
from typing import Any
class SubmissionUnavailableError(Exception):
pass
class SubmissionUploadError(Exception):
def __init__(self, file_path: str, status_code: int, content: Any) -> None:
self.status_code = status_code
self.content = content
super().__init__(f"Could not upload photo '{file_path}' due to HTTP {self.status_code}: {self.content}")
class SubmissionDuplicatesError(Exception):
def __init__(self, file_path: str, duplicates: list) -> None:
self.duplicates = duplicates
super().__init__(f"Found duplicates of a photo '{file_path}': {self.duplicates}")

View File

@ -7,6 +7,7 @@ from random import choice
from typing import Tuple, Union from typing import Tuple, Union
from requests import get, patch, post from requests import get, patch, post
from classes.exceptions import SubmissionUploadError
from modules.logger import logWrite from modules.logger import logWrite
from modules.utils import configGet from modules.utils import configGet
@ -59,7 +60,7 @@ async def upload_pic(filepath: str, token: Union[str, None] = None) -> Tuple[boo
response = post(f'{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos', params={"caption": "queue", "compress": False}, headers={"Authorization": f"Bearer {token}"}, files=files) response = post(f'{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos', params={"caption": "queue", "compress": False}, headers={"Authorization": f"Bearer {token}"}, files=files)
if response.status_code != 200 and response.status_code != 409: if response.status_code != 200 and response.status_code != 409:
logWrite(f"Could not upload '{filepath}' to API: HTTP {response.status_code} with message '{response.content}'") logWrite(f"Could not upload '{filepath}' to API: HTTP {response.status_code} with message '{response.content}'")
return False, [] raise SubmissionUploadError(str(filepath), response.status_code, response.content)
duplicates = [] duplicates = []
if "duplicates" in response.json(): if "duplicates" in response.json():
for duplicate in response.json()["duplicates"]: for duplicate in response.json()["duplicates"]:

View File

@ -1,4 +1,4 @@
from pyrogram.client import Client
from modules.utils import configGet from modules.utils import configGet
from classes.poster_client import PosterClient
app = Client("duptsiaposter", bot_token=configGet("bot_token", "bot"), api_id=configGet("api_id", "bot"), api_hash=configGet("api_hash", "bot")) app = PosterClient("duptsiaposter", bot_token=configGet("bot_token", "bot"), api_id=configGet("api_id", "bot"), api_hash=configGet("api_hash", "bot"))

View File

@ -1,10 +1,12 @@
from datetime import datetime, timezone from datetime import datetime, timezone
from os import makedirs, path, sep from os import makedirs, path, sep
from traceback import format_exc
from uuid import uuid4 from uuid import uuid4
from pyrogram import filters from pyrogram import filters
from pyrogram.client import Client from pyrogram.client import Client
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from classes.exceptions import SubmissionDuplicatesError
from modules.app import app from modules.app import app
from modules.database import col_banned, col_submitted from modules.database import col_banned, col_submitted
@ -141,6 +143,30 @@ async def get_submission(_: Client, msg: Message):
if msg.from_user.phone_number is not None: if msg.from_user.phone_number is not None:
caption += f" ({msg.from_user.phone_number})" caption += f" ({msg.from_user.phone_number})"
if msg.from_user.id == configGet("admin") and configGet("admins", "submission", "require_confirmation") is False:
try:
await app.submit_photo(str(inserted.inserted_id))
await msg.copy(configGet("admin"), caption=caption)
return
except SubmissionDuplicatesError as exp:
await msg.reply_text(locale("sub_media_duplicates_list", "message", locale=user_locale).format("\n".join(exp.duplicates)))
return
except Exception as exp:
await msg.reply_text(format_exc())
return
elif msg.from_user.id != configGet("admin") and configGet("users", "submission", "require_confirmation") is False:
try:
await app.submit_photo(str(inserted.inserted_id))
await msg.copy(configGet("admin"), caption=caption)
return
except SubmissionDuplicatesError as exp:
await msg.reply_text(locale("sub_media_duplicates_list", "message", locale=user_locale).format("\n".join(exp.duplicates)))
return
except Exception as exp:
await app.send_message(configGet("admin"), f"User {msg.from_user.id} could not submit photo without additional confirmation due to:\n```\n{format_exc()}\n```")
await msg.reply_text("Could not upload this image. Admins are advised.")
return
if msg.from_user.id != configGet("admin"): if msg.from_user.id != configGet("admin"):
buttons += [ buttons += [
[ [