API usage overhaul (#27)

* `/report` command added
* Updated to libbot 1.5
* Moved to [PhotosAPI_Client](https://git.end-play.xyz/profitroll/PhotosAPI_Client) v0.5.0 from using self-made API client
* Video support (almost stable)
* Bug fixes and improvements

Co-authored-by: profitroll <vozhd.kk@gmail.com>
Reviewed-on: #27
This commit is contained in:
2023-06-28 00:57:30 +03:00
parent f003638128
commit 5adb004a2a
29 changed files with 1332 additions and 1669 deletions

View File

@@ -1,32 +1,40 @@
import logging
from datetime import datetime
from os import makedirs, path, sep
from pathlib import Path
from traceback import format_exc
from uuid import uuid4
from pyrogram import filters
from pyrogram.client import Client
from pyrogram.enums.chat_action import ChatAction
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from classes.enums.submission_types import SubmissionType
from classes.exceptions import SubmissionDuplicatesError
from classes.poster_client import PosterClient
from classes.exceptions import SubmissionDuplicatesError, SubmissionUnsupportedError
from classes.pyroclient import PyroClient
from classes.user import PosterUser
from modules.app import app, users_with_context
from modules.database import col_banned, col_submitted
from modules.logger import logWrite
from modules.utils import configGet, locale
from modules.utils import USERS_WITH_CONTEXT
logger = logging.getLogger(__name__)
@app.on_message(
@Client.on_message(
~filters.scheduled & filters.private & filters.photo
| filters.video
| filters.animation
# | filters.animation
| filters.document
)
async def get_submission(app: PosterClient, msg: Message):
global users_with_context
if msg.from_user.id in users_with_context:
async def get_submission(app: PyroClient, msg: Message):
global USERS_WITH_CONTEXT
if not hasattr(msg.from_user, "id"):
return
if msg.from_user.id in USERS_WITH_CONTEXT:
return
try:
if col_banned.find_one({"user": msg.from_user.id}) is not None:
return
@@ -39,34 +47,37 @@ async def get_submission(app: PosterClient, msg: Message):
if PosterUser(msg.from_user.id).is_limited():
await msg.reply_text(
locale("sub_cooldown", "message", locale=user_locale).format(
str(configGet("timeout", "submission"))
app._("sub_cooldown", "message", locale=user_locale).format(
str(app.config["submission"]["timeout"])
)
)
return
if msg.document is not None:
logWrite(
f"User {msg.from_user.id} is trying to submit a file of type '{msg.document.mime_type}' with name '{msg.document.file_name}' and size of {msg.document.file_size / 1024 / 1024} MB",
debug=True,
logger.info(
"User %s is trying to submit a file of type '%s' with name '%s' and size of %s MB",
msg.from_user.id,
msg.document.mime_type,
msg.document.file_name,
msg.document.file_size / 1024 / 1024,
)
if msg.document.mime_type not in configGet("mime_types", "submission"):
if msg.document.mime_type not in app.config["submission"]["mime_types"]:
await msg.reply_text(
locale("mime_not_allowed", "message", locale=user_locale).format(
", ".join(configGet("mime_types", "submission"))
app._("mime_not_allowed", "message", locale=user_locale).format(
", ".join(app.config["submission"]["mime_types"])
),
quote=True,
)
return
if msg.document.file_size > configGet("file_size", "submission"):
if msg.document.file_size > app.config["submission"]["file_size"]:
await msg.reply_text(
locale("document_too_large", "message", locale=user_locale).format(
str(configGet("file_size", "submission") / 1024 / 1024)
app._("document_too_large", "message", locale=user_locale).format(
str(app.config["submission"]["file_size"] / 1024 / 1024)
),
quote=True,
)
return
if msg.document.file_size > configGet("tmp_size", "submission"):
if msg.document.file_size > app.config["submission"]["tmp_size"]:
save_tmp = False
contents = (
msg.document.file_id,
@@ -74,63 +85,72 @@ async def get_submission(app: PosterClient, msg: Message):
) # , msg.document.file_name
if msg.video is not None:
logWrite(
f"User {msg.from_user.id} is trying to submit a video with name '{msg.video.file_name}' and size of {msg.video.file_size / 1024 / 1024} MB",
debug=True,
logger.info(
"User %s is trying to submit a video with name '%s' and size of %s MB",
msg.from_user.id,
msg.video.file_name,
msg.video.file_size / 1024 / 1024,
)
if msg.video.file_size > configGet("file_size", "submission"):
if msg.video.file_size > app.config["submission"]["file_size"]:
await msg.reply_text(
locale("document_too_large", "message", locale=user_locale).format(
str(configGet("file_size", "submission") / 1024 / 1024)
app._("document_too_large", "message", locale=user_locale).format(
str(app.config["submission"]["file_size"] / 1024 / 1024)
),
quote=True,
)
return
if msg.video.file_size > configGet("tmp_size", "submission"):
if msg.video.file_size > app.config["submission"]["tmp_size"]:
save_tmp = False
contents = msg.video.file_id, SubmissionType.VIDEO # , msg.video.file_name
if msg.animation is not None:
logWrite(
f"User {msg.from_user.id} is trying to submit an animation with name '{msg.animation.file_name}' and size of {msg.animation.file_size / 1024 / 1024} MB",
debug=True,
)
if msg.animation.file_size > configGet("file_size", "submission"):
await msg.reply_text(
locale("document_too_large", "message", locale=user_locale).format(
str(configGet("file_size", "submission") / 1024 / 1024)
),
quote=True,
)
return
if msg.animation.file_size > configGet("tmp_size", "submission"):
save_tmp = False
contents = (
msg.animation.file_id,
SubmissionType.ANIMATION,
) # , msg.animation.file_name
# if msg.animation is not None:
# logger.info(
# "User %s is trying to submit an animation with name '%s' and size of %s MB",
# msg.from_user.id,
# msg.animation.file_name,
# msg.animation.file_size / 1024 / 1024,
# )
# if msg.animation.file_size > app.config["submission"]["file_size"]:
# await msg.reply_text(
# app._("document_too_large", "message", locale=user_locale).format(
# str(app.config["submission"]["file_size"] / 1024 / 1024)
# ),
# quote=True,
# )
# return
# if msg.animation.file_size > app.config["submission"]["tmp_size"]:
# save_tmp = False
# contents = (
# msg.animation.file_id,
# SubmissionType.ANIMATION,
# ) # , msg.animation.file_name
if msg.photo is not None:
logWrite(
f"User {msg.from_user.id} is trying to submit a photo with ID '{msg.photo.file_id}' and size of {msg.photo.file_size / 1024 / 1024} MB",
debug=True,
logger.info(
"User %s is trying to submit a photo with ID '%s' and size of %s MB",
msg.from_user.id,
msg.photo.file_id,
msg.photo.file_size / 1024 / 1024,
)
contents = msg.photo.file_id, SubmissionType.PHOTO # , "please_generate"
if save_tmp is not None:
if contents is None:
return
if contents is None:
return
if save_tmp is not None:
tmp_id = str(uuid4())
# filename = tmp_id if contents[1] == "please_generate" else contents[1]
makedirs(
path.join(configGet("data", "locations"), "submissions", tmp_id),
Path(f"{app.config['locations']['data']}/submissions/{tmp_id}"),
exist_ok=True,
)
downloaded = await app.download_media(
msg,
path.join(configGet("data", "locations"), "submissions", tmp_id) + sep,
str(Path(f"{app.config['locations']['data']}/submissions/{tmp_id}"))
+ sep,
)
inserted = col_submitted.insert_one(
{
"user": msg.from_user.id,
@@ -144,9 +164,6 @@ async def get_submission(app: PosterClient, msg: Message):
)
else:
if contents is None:
return
inserted = col_submitted.insert_one(
{
"user": msg.from_user.id,
@@ -162,7 +179,7 @@ async def get_submission(app: PosterClient, msg: Message):
buttons = [
[
InlineKeyboardButton(
text=locale("sub_yes", "button", locale=configGet("locale")),
text=app._("sub_yes", "button"),
callback_data=f"sub_yes_{str(inserted.inserted_id)}",
)
]
@@ -172,28 +189,20 @@ async def get_submission(app: PosterClient, msg: Message):
caption = str(msg.caption)
buttons[0].append(
InlineKeyboardButton(
text=locale(
"sub_yes_caption", "button", locale=configGet("locale")
),
text=app._("sub_yes_caption", "button"),
callback_data=f"sub_yes_{str(inserted.inserted_id)}_caption",
)
)
buttons[0].append(
InlineKeyboardButton(
text=locale("sub_no", "button", locale=configGet("locale")),
callback_data=f"sub_no_{str(inserted.inserted_id)}",
)
)
else:
caption = ""
buttons[0].append(
InlineKeyboardButton(
text=locale("sub_no", "button", locale=configGet("locale")),
callback_data=f"sub_no_{str(inserted.inserted_id)}",
)
)
caption += locale("sub_by", "message", locale=locale(configGet("locale")))
buttons[0].append(
InlineKeyboardButton(
text=app._("sub_no", "button"),
callback_data=f"sub_no_{str(inserted.inserted_id)}",
)
)
caption += app._("sub_by", "message")
if msg.from_user.first_name is not None:
caption += f" {msg.from_user.first_name}"
@@ -206,22 +215,30 @@ async def get_submission(app: PosterClient, msg: Message):
if (
msg.from_user.id in app.admins
and configGet("admins", "submission", "require_confirmation") is False
and app.config["submission"]["require_confirmation"]["admins"] is False
):
try:
submitted = await app.submit_photo(str(inserted.inserted_id))
submitted = await app.submit_media(str(inserted.inserted_id))
await msg.reply_text(
locale("sub_yes_auto", "message", locale=user_locale),
app._("sub_yes_auto", "message", locale=user_locale),
disable_notification=True,
quote=True,
)
if configGet("send_uploaded_id", "submission"):
if app.config["submission"]["send_uploaded_id"]:
caption += f"\n\nID: `{submitted[1]}`"
await msg.copy(app.owner, caption=caption, disable_notification=True)
return
except SubmissionUnsupportedError:
await msg.reply_text(
app._("mime_not_allowed", "message", locale=user_locale).format(
", ".join(app.config["submission"]["mime_types"]), quote=True
),
quote=True,
)
return
except SubmissionDuplicatesError as exp:
await msg.reply_text(
locale(
app._(
"sub_media_duplicates_list", "message", locale=user_locale
).format("\n".join(exp.duplicates)),
quote=True,
@@ -232,28 +249,35 @@ async def get_submission(app: PosterClient, msg: Message):
return
elif (
msg.from_user.id not in app.admins
and configGet("users", "submission", "require_confirmation") is False
and app.config["submission"]["require_confirmation"]["users"] is False
):
try:
submitted = await app.submit_photo(str(inserted.inserted_id))
await msg.reply_text(
locale("sub_yes_auto", "message", locale=user_locale),
app._("sub_yes_auto", "message", locale=user_locale),
disable_notification=True,
quote=True,
)
if configGet("send_uploaded_id", "submission"):
if app.config["submission"]["send_uploaded_id"]:
caption += f"\n\nID: `{submitted[1]}`"
await msg.copy(app.owner, caption=caption)
return
except SubmissionUnsupportedError:
await msg.reply_text(
app._("mime_not_allowed", "message", locale=user_locale).format(
", ".join(app.config["submission"]["mime_types"]), quote=True
)
)
return
except SubmissionDuplicatesError as exp:
await msg.reply_text(
locale("sub_dup", "message", locale=user_locale), quote=True
app._("sub_dup", "message", locale=user_locale), quote=True
)
return
except Exception as exp:
await app.send_message(
app.owner,
locale("sub_error_admin", "message").format(
app._("sub_error_admin", "message").format(
msg.from_user.id, format_exc()
),
)
@@ -264,7 +288,7 @@ async def get_submission(app: PosterClient, msg: Message):
buttons += [
[
InlineKeyboardButton(
text=locale("sub_block", "button", locale=configGet("locale")),
text=app._("sub_block", "button"),
callback_data=f"sub_block_{msg.from_user.id}",
)
]
@@ -274,7 +298,7 @@ async def get_submission(app: PosterClient, msg: Message):
if msg.from_user.id != app.owner:
await msg.reply_text(
locale("sub_sent", "message", locale=user_locale),
app._("sub_sent", "message", locale=user_locale),
disable_notification=True,
quote=True,
)
@@ -284,4 +308,4 @@ async def get_submission(app: PosterClient, msg: Message):
)
except AttributeError:
logWrite(f"from_user in function get_submission does not seem to contain id")
logger.error("'from_user' does not seem to contain 'id'")