WIP: /language system

This commit is contained in:
Profitroll 2023-06-28 10:37:18 +02:00
parent 6f8b560acc
commit 10c60ae932
Signed by: profitroll
GPG Key ID: FA35CAB49DACD3B2
9 changed files with 203 additions and 205 deletions

View File

@ -1,58 +0,0 @@
from datetime import datetime
from libbot import sync
from modules.database import col_banned, col_users
class PosterUser:
def __init__(self, id: int):
self.id = id
def is_blocked(self) -> bool:
"""Check if user is banned from submitting content.
### Returns:
`bool`: Must be `True` if banned and `False` if not
"""
return False if col_banned.find_one({"user": self.id}) is None else True
def block(self) -> None:
"""Ban user from using command and submitting content."""
if col_banned.find_one({"user": self.id}) is None:
col_banned.insert_one({"user": self.id, "date": datetime.now()})
def unblock(self) -> None:
"""Allow user to use command and submit posts again."""
col_banned.find_one_and_delete({"user": self.id})
def is_limited(self) -> bool:
"""Check if user is on a cooldown after submitting something.
### Returns:
`bool`: Must be `True` if on the cooldown and `False` if not
"""
if self.id in sync.config_get("admins", "bot"):
return False
db_record = col_users.find_one({"user": self.id})
if db_record is None:
return False
return (
True
if (datetime.now() - db_record["cooldown"]).total_seconds()
< sync.config_get("timeout", "submission")
else False
)
def limit(self) -> None:
"""Restart user's cooldown. Used after post has been submitted."""
if (
col_users.find_one_and_update(
{"user": self.id}, {"$set": {"cooldown": datetime.now()}}
)
is None
):
col_users.insert_one({"user": self.id, "cooldown": datetime.now()})

View File

@ -7,6 +7,6 @@ from classes.pyroclient import PyroClient
@Client.on_callback_query(filters.regex("nothing")) @Client.on_callback_query(filters.regex("nothing"))
async def callback_query_nothing(app: PyroClient, clb: CallbackQuery): async def callback_query_nothing(app: PyroClient, clb: CallbackQuery):
await clb.answer( user = await app.find_user(clb.from_user)
text=app._("nothing", "callback", locale=clb.from_user.language_code)
) await clb.answer(text=app._("nothing", "callback", locale=user.locale))

View File

@ -15,7 +15,6 @@ from classes.exceptions import (
SubmissionUnsupportedError, SubmissionUnsupportedError,
) )
from classes.pyroclient import PyroClient from classes.pyroclient import PyroClient
from classes.user import PosterUser
from modules.database import col_submitted from modules.database import col_submitted
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -23,22 +22,22 @@ logger = logging.getLogger(__name__)
@Client.on_callback_query(filters.regex("sub_yes_[\s\S]*")) @Client.on_callback_query(filters.regex("sub_yes_[\s\S]*"))
async def callback_query_yes(app: PyroClient, clb: CallbackQuery): async def callback_query_yes(app: PyroClient, clb: CallbackQuery):
user = await app.find_user(clb.from_user)
fullclb = str(clb.data).split("_") fullclb = str(clb.data).split("_")
user_locale = clb.from_user.language_code
db_entry = col_submitted.find_one({"_id": ObjectId(fullclb[2])}) db_entry = col_submitted.find_one({"_id": ObjectId(fullclb[2])})
try: try:
submission = await app.submit_photo(fullclb[2]) submission = await app.submit_media(fullclb[2])
except SubmissionUnavailableError: except SubmissionUnavailableError:
await clb.answer( await clb.answer(
text=app._("sub_msg_unavail", "callback", locale=user_locale), text=app._("sub_msg_unavail", "callback", locale=user.locale),
show_alert=True, show_alert=True,
) )
return return
except SubmissionUnsupportedError: except SubmissionUnsupportedError:
await clb.answer( await clb.answer(
text=app._("mime_not_allowed", "message", locale=user_locale).format( text=app._("mime_not_allowed", "message", locale=user.locale).format(
", ".join(app.config["submission"]["mime_types"]), quote=True ", ".join(app.config["submission"]["mime_types"]), quote=True
), ),
show_alert=True, show_alert=True,
@ -46,11 +45,11 @@ async def callback_query_yes(app: PyroClient, clb: CallbackQuery):
return return
except SubmissionDuplicatesError as exp: except SubmissionDuplicatesError as exp:
await clb.answer( await clb.answer(
text=app._("sub_duplicates_found", "callback", locale=user_locale), text=app._("sub_duplicates_found", "callback", locale=user.locale),
show_alert=True, show_alert=True,
) )
await clb.message.reply_text( await clb.message.reply_text(
app._("sub_media_duplicates_list", "message", locale=user_locale).format( app._("sub_media_duplicates_list", "message", locale=user.locale).format(
"\n".join(exp.duplicates) "\n".join(exp.duplicates)
), ),
quote=True, quote=True,
@ -69,14 +68,25 @@ async def callback_query_yes(app: PyroClient, clb: CallbackQuery):
if submission[0] is not None: if submission[0] is not None:
await submission[0].reply_text( await submission[0].reply_text(
app._("sub_yes", "message", locale=submission[0].from_user.language_code), app._(
"sub_yes",
"message",
locale=(await app.find_user(submission[0].from_user)).locale,
),
quote=True, quote=True,
) )
elif db_entry is not None: elif db_entry is not None:
await app.send_message(db_entry["user"], app._("sub_yes", "message")) await app.send_message(
db_entry["user"],
app._(
"sub_yes",
"message",
locale=(await app.find_user(db_entry["user"])).locale,
),
)
await clb.answer( await clb.answer(
text=app._("sub_yes", "callback", locale=user_locale).format(fullclb[2]), text=app._("sub_yes", "callback", locale=user.locale).format(fullclb[2]),
show_alert=True, show_alert=True,
) )
@ -84,7 +94,7 @@ async def callback_query_yes(app: PyroClient, clb: CallbackQuery):
[ [
[ [
InlineKeyboardButton( InlineKeyboardButton(
text=str(app._("accepted", "button", locale=user_locale)), text=str(app._("accepted", "button", locale=user.locale)),
callback_data="nothing", callback_data="nothing",
) )
], ],
@ -94,7 +104,7 @@ async def callback_query_yes(app: PyroClient, clb: CallbackQuery):
else [ else [
[ [
InlineKeyboardButton( InlineKeyboardButton(
text=str(app._("accepted", "button", locale=user_locale)), text=str(app._("accepted", "button", locale=user.locale)),
callback_data="nothing", callback_data="nothing",
) )
] ]
@ -103,7 +113,7 @@ async def callback_query_yes(app: PyroClient, clb: CallbackQuery):
if await config_get("send_uploaded_id", "submission"): if await config_get("send_uploaded_id", "submission"):
await clb.message.edit_caption( await clb.message.edit_caption(
clb.message.caption + f"\n\nID: `{submission[1]}`" f"{clb.message.caption}\n\nID: `{submission[1]}`"
) )
await clb.message.edit_reply_markup( await clb.message.edit_reply_markup(
@ -121,8 +131,8 @@ async def callback_query_yes(app: PyroClient, clb: CallbackQuery):
@Client.on_callback_query(filters.regex("sub_no_[\s\S]*")) @Client.on_callback_query(filters.regex("sub_no_[\s\S]*"))
async def callback_query_no(app: PyroClient, clb: CallbackQuery): async def callback_query_no(app: PyroClient, clb: CallbackQuery):
user = await app.find_user(clb.from_user)
fullclb = str(clb.data).split("_") fullclb = str(clb.data).split("_")
user_locale = clb.from_user.language_code
db_entry = col_submitted.find_one_and_delete({"_id": ObjectId(fullclb[2])}) db_entry = col_submitted.find_one_and_delete({"_id": ObjectId(fullclb[2])})
@ -145,17 +155,21 @@ async def callback_query_no(app: PyroClient, clb: CallbackQuery):
) )
except Exception as exp: except Exception as exp:
await clb.answer( await clb.answer(
text=app._("sub_msg_unavail", "message", locale=user_locale), text=app._("sub_msg_unavail", "message", locale=user.locale),
show_alert=True, show_alert=True,
) )
return return
await submission.reply_text( await submission.reply_text(
app._("sub_no", "message", locale=submission.from_user.language_code), app._(
"sub_no",
"message",
locale=(await app.find_user(submission.from_user)).locale,
),
quote=True, quote=True,
) )
await clb.answer( await clb.answer(
text=app._("sub_no", "callback", locale=user_locale).format(fullclb[2]), text=app._("sub_no", "callback", locale=user.locale).format(fullclb[2]),
show_alert=True, show_alert=True,
) )
@ -163,7 +177,7 @@ async def callback_query_no(app: PyroClient, clb: CallbackQuery):
[ [
[ [
InlineKeyboardButton( InlineKeyboardButton(
text=str(app._("declined", "button", locale=user_locale)), text=str(app._("declined", "button", locale=user.locale)),
callback_data="nothing", callback_data="nothing",
) )
], ],
@ -173,7 +187,7 @@ async def callback_query_no(app: PyroClient, clb: CallbackQuery):
else [ else [
[ [
InlineKeyboardButton( InlineKeyboardButton(
text=str(app._("declined", "button", locale=user_locale)), text=str(app._("declined", "button", locale=user.locale)),
callback_data="nothing", callback_data="nothing",
) )
] ]
@ -193,17 +207,21 @@ async def callback_query_no(app: PyroClient, clb: CallbackQuery):
@Client.on_callback_query(filters.regex("sub_block_[\s\S]*")) @Client.on_callback_query(filters.regex("sub_block_[\s\S]*"))
async def callback_query_block(app: PyroClient, clb: CallbackQuery): async def callback_query_block(app: PyroClient, clb: CallbackQuery):
user = await app.find_user(clb.from_user)
fullclb = str(clb.data).split("_") fullclb = str(clb.data).split("_")
user_locale = clb.from_user.language_code
await app.send_message( await app.send_message(
int(fullclb[2]), int(fullclb[2]),
app._("sub_blocked", "message"), app._(
"sub_blocked",
"message",
locale=(await app.find_user(int(fullclb[2]))).locale,
),
) )
PosterUser(int(fullclb[2])).block() await user.block()
await clb.answer( await clb.answer(
text=app._("sub_block", "callback", locale=user_locale).format(fullclb[2]), text=app._("sub_block", "callback", locale=user.locale).format(fullclb[2]),
show_alert=True, show_alert=True,
) )
@ -211,7 +229,7 @@ async def callback_query_block(app: PyroClient, clb: CallbackQuery):
clb.message.reply_markup.inline_keyboard[0], clb.message.reply_markup.inline_keyboard[0],
[ [
InlineKeyboardButton( InlineKeyboardButton(
text=str(app._("sub_unblock", "button", locale=user_locale)), text=str(app._("sub_unblock", "button", locale=user.locale)),
callback_data=f"sub_unblock_{fullclb[2]}", callback_data=f"sub_unblock_{fullclb[2]}",
) )
], ],
@ -230,15 +248,22 @@ async def callback_query_block(app: PyroClient, clb: CallbackQuery):
@Client.on_callback_query(filters.regex("sub_unblock_[\s\S]*")) @Client.on_callback_query(filters.regex("sub_unblock_[\s\S]*"))
async def callback_query_unblock(app: PyroClient, clb: CallbackQuery): async def callback_query_unblock(app: PyroClient, clb: CallbackQuery):
user = await app.find_user(clb.from_user)
fullclb = str(clb.data).split("_") fullclb = str(clb.data).split("_")
user_locale = clb.from_user.language_code
await app.send_message(int(fullclb[2]), app._("sub_unblocked", "message")) await app.send_message(
int(fullclb[2]),
app._(
"sub_unblocked",
"message",
locale=(await app.find_user(int(fullclb[2]))).locale,
),
)
PosterUser(int(fullclb[2])).unblock() await user.unblock()
await clb.answer( await clb.answer(
text=app._("sub_unblock", "callback", locale=user_locale).format(fullclb[2]), text=app._("sub_unblock", "callback", locale=user.locale).format(fullclb[2]),
show_alert=True, show_alert=True,
) )
@ -246,7 +271,7 @@ async def callback_query_unblock(app: PyroClient, clb: CallbackQuery):
clb.message.reply_markup.inline_keyboard[0], clb.message.reply_markup.inline_keyboard[0],
[ [
InlineKeyboardButton( InlineKeyboardButton(
text=str(app._("sub_block", "button", locale=user_locale)), text=str(app._("sub_block", "button", locale=user.locale)),
callback_data=f"sub_block_{fullclb[2]}", callback_data=f"sub_block_{fullclb[2]}",
) )
], ],

View File

@ -18,16 +18,18 @@ async def cmd_kill(app: PyroClient, msg: Message):
if msg.from_user.id not in app.admins: if msg.from_user.id not in app.admins:
return return
user = await app.find_user(msg.from_user)
if len(USERS_WITH_CONTEXT) > 0: if len(USERS_WITH_CONTEXT) > 0:
await msg.reply_text( await msg.reply_text(
app._("shutdown_confirm", "message").format(len(USERS_WITH_CONTEXT)), app._("shutdown_confirm", "message", locale=user.locale).format(
len(USERS_WITH_CONTEXT)
),
reply_markup=InlineKeyboardMarkup( reply_markup=InlineKeyboardMarkup(
[ [
[ [
InlineKeyboardButton( InlineKeyboardButton(
app._( app._("shutdown", "button", locale=user.locale),
"shutdown", "button", locale=msg.from_user.language_code
),
callback_data="shutdown", callback_data="shutdown",
) )
] ]

View File

@ -3,22 +3,25 @@ from pyrogram.client import Client
from pyrogram.types import Message from pyrogram.types import Message
from classes.pyroclient import PyroClient from classes.pyroclient import PyroClient
from classes.user import PosterUser
@Client.on_message(~filters.scheduled & filters.command(["start"], prefixes="/")) @Client.on_message(~filters.scheduled & filters.command(["start"], prefixes="/"))
async def cmd_start(app: PyroClient, msg: Message): async def cmd_start(app: PyroClient, msg: Message):
if PosterUser(msg.from_user.id).is_blocked(): user = await app.find_user(msg.from_user)
if user.banned:
return return
await msg.reply_text(app._("start", "message", locale=msg.from_user.language_code)) await msg.reply_text(app._("start", "message", locale=user.locale))
@Client.on_message( @Client.on_message(
~filters.scheduled & filters.command(["rules", "help"], prefixes="/") ~filters.scheduled & filters.command(["rules", "help"], prefixes="/")
) )
async def cmd_rules(app: PyroClient, msg: Message): async def cmd_rules(app: PyroClient, msg: Message):
if PosterUser(msg.from_user.id).is_blocked(): user = await app.find_user(msg.from_user)
if user.banned:
return return
await msg.reply_text(app._("rules", "message", locale=msg.from_user.language_code)) await msg.reply_text(app._("rules", "message", locale=user.locale))

View File

@ -48,9 +48,9 @@ async def cmd_import(app: PyroClient, msg: Message):
else: else:
return return
await msg.reply_text( user = await app.find_user(msg.from_user)
app._("import_request", "message", locale=msg.from_user.language_code)
) await msg.reply_text(app._("import_request", "message", locale=user.locale))
answer = await listen_message(app, msg.chat.id, timeout=600) answer = await listen_message(app, msg.chat.id, timeout=600)
@ -58,15 +58,13 @@ async def cmd_import(app: PyroClient, msg: Message):
if answer is None: if answer is None:
await msg.reply_text( await msg.reply_text(
app._("import_ignored", "message", locale=msg.from_user.language_code), app._("import_ignored", "message", locale=user.locale),
quote=True, quote=True,
) )
return return
if answer.text == "/cancel": if answer.text == "/cancel":
await answer.reply_text( await answer.reply_text(app._("import_abort", "message", locale=user.locale))
app._("import_abort", "message", locale=msg.from_user.language_code)
)
return return
if answer.document is None: if answer.document is None:
@ -74,7 +72,7 @@ async def cmd_import(app: PyroClient, msg: Message):
app._( app._(
"import_invalid_media", "import_invalid_media",
"message", "message",
locale=msg.from_user.language_code, locale=user.locale,
), ),
quote=True, quote=True,
) )
@ -82,16 +80,14 @@ async def cmd_import(app: PyroClient, msg: Message):
if answer.document.mime_type != "application/zip": if answer.document.mime_type != "application/zip":
await answer.reply_text( await answer.reply_text(
app._("import_invalid_mime", "message", locale=msg.from_user.language_code), app._("import_invalid_mime", "message", locale=user.locale),
quote=True, quote=True,
) )
return return
if disk_usage(getcwd())[2] < (answer.document.file_size) * 3: if disk_usage(getcwd())[2] < (answer.document.file_size) * 3:
await msg.reply_text( await msg.reply_text(
app._( app._("import_too_big", "message", locale=user.locale).format(
"import_too_big", "message", locale=msg.from_user.language_code
).format(
answer.document.file_size // (2**30), answer.document.file_size // (2**30),
disk_usage(getcwd())[2] // (2**30), disk_usage(getcwd())[2] // (2**30),
) )
@ -111,14 +107,12 @@ async def cmd_import(app: PyroClient, msg: Message):
tmp_path = Path(f"{app.config['locations']['tmp']}/{answer.document.file_id}") tmp_path = Path(f"{app.config['locations']['tmp']}/{answer.document.file_id}")
downloading = await answer.reply_text( downloading = await answer.reply_text(
app._("import_downloading", "message", locale=msg.from_user.language_code), app._("import_downloading", "message", locale=user.locale),
quote=True, quote=True,
) )
await app.download_media(answer, file_name=str(tmp_path)) await app.download_media(answer, file_name=str(tmp_path))
await downloading.edit( await downloading.edit(app._("import_unpacking", "message", locale=user.locale))
app._("import_unpacking", "message", locale=msg.from_user.language_code)
)
try: try:
with ZipFile(tmp_path, "r") as handle: with ZipFile(tmp_path, "r") as handle:
@ -137,17 +131,15 @@ async def cmd_import(app: PyroClient, msg: Message):
format_exc(), format_exc(),
) )
await answer.reply_text( await answer.reply_text(
app._( app._("import_unpack_error", "message", locale=user.locale).format(
"import_unpack_error", "message", locale=msg.from_user.language_code exp, format_exc()
).format(exp, format_exc()) )
) )
return return
logger.info("Downloaded '%s' - awaiting upload", answer.document.file_name) logger.info("Downloaded '%s' - awaiting upload", answer.document.file_name)
await downloading.edit( await downloading.edit(app._("import_uploading", "message", locale=user.locale))
app._("import_uploading", "message", locale=msg.from_user.language_code)
)
remove(tmp_path) remove(tmp_path)
@ -184,7 +176,7 @@ async def cmd_import(app: PyroClient, msg: Message):
app._( app._(
"import_upload_error_other", "import_upload_error_other",
"message", "message",
locale=msg.from_user.language_code, locale=user.locale,
).format(path.basename(filename)), ).format(path.basename(filename)),
disable_notification=True, disable_notification=True,
) )
@ -205,7 +197,7 @@ async def cmd_import(app: PyroClient, msg: Message):
app._( app._(
"import_upload_error_duplicate", "import_upload_error_duplicate",
"message", "message",
locale=msg.from_user.language_code, locale=user.locale,
).format(path.basename(filename)), ).format(path.basename(filename)),
disable_notification=True, disable_notification=True,
) )
@ -214,7 +206,7 @@ async def cmd_import(app: PyroClient, msg: Message):
app._( app._(
"import_upload_error_other", "import_upload_error_other",
"message", "message",
locale=msg.from_user.language_code, locale=user.locale,
).format(path.basename(filename)), ).format(path.basename(filename)),
disable_notification=True, disable_notification=True,
) )
@ -235,7 +227,7 @@ async def cmd_import(app: PyroClient, msg: Message):
rmtree(Path(f"{app.config['locations']['tmp']}/{tmp_dir}"), ignore_errors=True) rmtree(Path(f"{app.config['locations']['tmp']}/{tmp_dir}"), ignore_errors=True)
await answer.reply_text( await answer.reply_text(
app._("import_finished", "message", locale=msg.from_user.language_code), app._("import_finished", "message", locale=user.locale),
quote=True, quote=True,
) )
@ -260,9 +252,9 @@ async def cmd_remove(app: PyroClient, msg: Message):
else: else:
return return
await msg.reply_text( user = await app.find_user(msg.from_user)
app._("remove_request", "message", locale=msg.from_user.language_code)
) await msg.reply_text(app._("remove_request", "message", locale=user.locale))
answer_id = await listen_message(app, msg.chat.id, timeout=600) answer_id = await listen_message(app, msg.chat.id, timeout=600)
@ -270,28 +262,22 @@ async def cmd_remove(app: PyroClient, msg: Message):
if answer_id is None: if answer_id is None:
await msg.reply_text( await msg.reply_text(
app._("remove_ignored", "message", locale=msg.from_user.language_code), app._("remove_ignored", "message", locale=user.locale),
quote=True, quote=True,
) )
return return
if answer_id.text == "/cancel": if answer_id.text == "/cancel":
await answer_id.reply_text( await answer_id.reply_text(app._("remove_abort", "message", locale=user.locale))
app._("remove_abort", "message", locale=msg.from_user.language_code)
)
return return
await msg.reply_text( await msg.reply_text(
app._("remove_kind", "message", locale=msg.from_user.language_code), app._("remove_kind", "message", locale=user.locale),
reply_markup=ReplyKeyboardMarkup( reply_markup=ReplyKeyboardMarkup(
[ [
[ [
KeyboardButton( KeyboardButton(app._("photo", "button", locale=user.locale)),
app._("photo", "button", locale=msg.from_user.language_code) KeyboardButton(app._("video", "button", locale=user.locale)),
),
KeyboardButton(
app._("video", "button", locale=msg.from_user.language_code)
),
] ]
], ],
resize_keyboard=True, resize_keyboard=True,
@ -307,7 +293,7 @@ async def cmd_remove(app: PyroClient, msg: Message):
if answer_kind is None: if answer_kind is None:
await msg.reply_text( await msg.reply_text(
app._("remove_ignored", "message", locale=msg.from_user.language_code), app._("remove_ignored", "message", locale=user.locale),
quote=True, quote=True,
reply_markup=ReplyKeyboardRemove(), reply_markup=ReplyKeyboardRemove(),
) )
@ -315,7 +301,7 @@ async def cmd_remove(app: PyroClient, msg: Message):
if answer_kind.text == "/cancel": if answer_kind.text == "/cancel":
await answer_kind.reply_text( await answer_kind.reply_text(
app._("remove_abort", "message", locale=msg.from_user.language_code), app._("remove_abort", "message", locale=user.locale),
reply_markup=ReplyKeyboardRemove(), reply_markup=ReplyKeyboardRemove(),
) )
return return
@ -326,11 +312,9 @@ async def cmd_remove(app: PyroClient, msg: Message):
func = video_delete func = video_delete
else: else:
await answer_kind.reply_text( await answer_kind.reply_text(
app._( app._("remove_unknown", "message", locale=user.locale).format(
"remove_unknown", "message", locale=msg.from_user.language_code app._("photo", "button", locale=user.locale),
).format( app._("video", "button", locale=user.locale),
app._("photo", "button", locale=msg.from_user.language_code),
app._("video", "button", locale=msg.from_user.language_code),
), ),
reply_markup=ReplyKeyboardRemove(), reply_markup=ReplyKeyboardRemove(),
) )
@ -346,9 +330,9 @@ async def cmd_remove(app: PyroClient, msg: Message):
answer_id.from_user.id, answer_id.from_user.id,
) )
await answer_kind.reply_text( await answer_kind.reply_text(
app._( app._("remove_success", "message", locale=user.locale).format(
"remove_success", "message", locale=msg.from_user.language_code answer_id.text
).format(answer_id.text), ),
reply_markup=ReplyKeyboardRemove(), reply_markup=ReplyKeyboardRemove(),
) )
else: else:
@ -359,9 +343,9 @@ async def cmd_remove(app: PyroClient, msg: Message):
answer_id.from_user.id, answer_id.from_user.id,
) )
await answer_kind.reply_text( await answer_kind.reply_text(
app._( app._("remove_failure", "message", locale=user.locale).format(
"remove_failure", "message", locale=msg.from_user.language_code answer_id.text
).format(answer_id.text), ),
reply_markup=ReplyKeyboardRemove(), reply_markup=ReplyKeyboardRemove(),
) )

View File

@ -1,7 +1,8 @@
from pyrogram.client import Client
from pyrogram import filters
from pyrogram.types import Message, User
from libbot import sync from libbot import sync
from pyrogram import filters
from pyrogram.client import Client
from pyrogram.types import Message, User
from classes.pyroclient import PyroClient from classes.pyroclient import PyroClient
@ -12,31 +13,29 @@ from classes.pyroclient import PyroClient
& filters.command(["report"], prefixes=["", "/"]) & filters.command(["report"], prefixes=["", "/"])
) )
async def command_report(app: PyroClient, msg: Message): async def command_report(app: PyroClient, msg: Message):
if msg.reply_to_message.forward_from_chat.id == app.config["posting"]["channel"]: if msg.reply_to_message.forward_from_chat.id != app.config["posting"]["channel"]:
await msg.reply_text( return
app._(
"report_sent", user = await app.find_user(msg.from_user)
"message",
locale=msg.from_user.language_code await msg.reply_text(
if msg.from_user is not None app._(
else None, "report_sent",
) "message",
locale=user.locale if msg.from_user is not None else None,
) )
)
print(msg) print(msg)
report_sent = await msg.reply_to_message.forward(app.owner) report_sent = await msg.reply_to_message.forward(app.owner)
sender = msg.from_user if msg.from_user is not None else msg.sender_chat sender = msg.from_user if msg.from_user is not None else msg.sender_chat
sender_name = ( sender_name = sender.first_name if isinstance(sender, User) else sender.title
sender.first_name if isinstance(sender, User) else sender.title
)
# ACTION NEEDED await report_sent.reply_text(
# Name and username are somehow None app._("report_received", "message", locale=user.locale).format(
await report_sent.reply_text( sender_name, sender.username, sender.id
app._("report_received", "message").format( ),
sender_name, sender.username, sender.id quote=True,
), )
quote=True,
)

View File

@ -13,7 +13,6 @@ from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from classes.enums.submission_types import SubmissionType from classes.enums.submission_types import SubmissionType
from classes.exceptions import SubmissionDuplicatesError, SubmissionUnsupportedError from classes.exceptions import SubmissionDuplicatesError, SubmissionUnsupportedError
from classes.pyroclient import PyroClient from classes.pyroclient import PyroClient
from classes.user import PosterUser
from modules.database import col_banned, col_submitted from modules.database import col_banned, col_submitted
from modules.utils import USERS_WITH_CONTEXT from modules.utils import USERS_WITH_CONTEXT
@ -35,20 +34,22 @@ async def get_submission(app: PyroClient, msg: Message):
if msg.from_user.id in USERS_WITH_CONTEXT: if msg.from_user.id in USERS_WITH_CONTEXT:
return return
user = await app.find_user(msg.from_user)
user_owner = await app.find_user(app.owner)
try: try:
if col_banned.find_one({"user": msg.from_user.id}) is not None: if col_banned.find_one({"user": msg.from_user.id}) is not None:
return return
await app.send_chat_action(msg.chat.id, ChatAction.TYPING) await app.send_chat_action(msg.chat.id, ChatAction.TYPING)
user_locale = msg.from_user.language_code
save_tmp = True save_tmp = True
contents = None contents = None
if PosterUser(msg.from_user.id).is_limited(): if await user.is_limited():
await msg.reply_text( await msg.reply_text(
app._("sub_cooldown", "message", locale=user_locale).format( app._("sub_cooldown", "message", locale=user.locale).format(
str(app.config["submission"]["timeout"]) app.config["submission"]["timeout"]
) )
) )
return return
@ -63,7 +64,7 @@ async def get_submission(app: PyroClient, msg: Message):
) )
if msg.document.mime_type not in app.config["submission"]["mime_types"]: if msg.document.mime_type not in app.config["submission"]["mime_types"]:
await msg.reply_text( await msg.reply_text(
app._("mime_not_allowed", "message", locale=user_locale).format( app._("mime_not_allowed", "message", locale=user.locale).format(
", ".join(app.config["submission"]["mime_types"]) ", ".join(app.config["submission"]["mime_types"])
), ),
quote=True, quote=True,
@ -71,8 +72,8 @@ async def get_submission(app: PyroClient, msg: Message):
return return
if msg.document.file_size > app.config["submission"]["file_size"]: if msg.document.file_size > app.config["submission"]["file_size"]:
await msg.reply_text( await msg.reply_text(
app._("document_too_large", "message", locale=user_locale).format( app._("document_too_large", "message", locale=user.locale).format(
str(app.config["submission"]["file_size"] / 1024 / 1024) app.config["submission"]["file_size"] / 1024 / 1024
), ),
quote=True, quote=True,
) )
@ -93,8 +94,8 @@ async def get_submission(app: PyroClient, msg: Message):
) )
if msg.video.file_size > app.config["submission"]["file_size"]: if msg.video.file_size > app.config["submission"]["file_size"]:
await msg.reply_text( await msg.reply_text(
app._("document_too_large", "message", locale=user_locale).format( app._("document_too_large", "message", locale=user.locale).format(
str(app.config["submission"]["file_size"] / 1024 / 1024) app.config["submission"]["file_size"] / 1024 / 1024
), ),
quote=True, quote=True,
) )
@ -112,7 +113,7 @@ async def get_submission(app: PyroClient, msg: Message):
# ) # )
# if msg.animation.file_size > app.config["submission"]["file_size"]: # if msg.animation.file_size > app.config["submission"]["file_size"]:
# await msg.reply_text( # await msg.reply_text(
# app._("document_too_large", "message", locale=user_locale).format( # app._("document_too_large", "message", locale=user.locale).format(
# str(app.config["submission"]["file_size"] / 1024 / 1024) # str(app.config["submission"]["file_size"] / 1024 / 1024)
# ), # ),
# quote=True, # quote=True,
@ -179,7 +180,7 @@ async def get_submission(app: PyroClient, msg: Message):
buttons = [ buttons = [
[ [
InlineKeyboardButton( InlineKeyboardButton(
text=app._("sub_yes", "button"), text=app._("sub_yes", "button", locale=user_owner.locale),
callback_data=f"sub_yes_{str(inserted.inserted_id)}", callback_data=f"sub_yes_{str(inserted.inserted_id)}",
) )
] ]
@ -189,7 +190,7 @@ async def get_submission(app: PyroClient, msg: Message):
caption = str(msg.caption) caption = str(msg.caption)
buttons[0].append( buttons[0].append(
InlineKeyboardButton( InlineKeyboardButton(
text=app._("sub_yes_caption", "button"), text=app._("sub_yes_caption", "button", locale=user_owner.locale),
callback_data=f"sub_yes_{str(inserted.inserted_id)}_caption", callback_data=f"sub_yes_{str(inserted.inserted_id)}_caption",
) )
) )
@ -198,11 +199,11 @@ async def get_submission(app: PyroClient, msg: Message):
buttons[0].append( buttons[0].append(
InlineKeyboardButton( InlineKeyboardButton(
text=app._("sub_no", "button"), text=app._("sub_no", "button", locale=user_owner.locale),
callback_data=f"sub_no_{str(inserted.inserted_id)}", callback_data=f"sub_no_{str(inserted.inserted_id)}",
) )
) )
caption += app._("sub_by", "message") caption += app._("sub_by", "message", locale=user_owner.locale)
if msg.from_user.first_name is not None: if msg.from_user.first_name is not None:
caption += f" {msg.from_user.first_name}" caption += f" {msg.from_user.first_name}"
@ -220,7 +221,7 @@ async def get_submission(app: PyroClient, msg: Message):
try: try:
submitted = await app.submit_media(str(inserted.inserted_id)) submitted = await app.submit_media(str(inserted.inserted_id))
await msg.reply_text( await msg.reply_text(
app._("sub_yes_auto", "message", locale=user_locale), app._("sub_yes_auto", "message", locale=user.locale),
disable_notification=True, disable_notification=True,
quote=True, quote=True,
) )
@ -230,7 +231,7 @@ async def get_submission(app: PyroClient, msg: Message):
return return
except SubmissionUnsupportedError: except SubmissionUnsupportedError:
await msg.reply_text( await msg.reply_text(
app._("mime_not_allowed", "message", locale=user_locale).format( app._("mime_not_allowed", "message", locale=user.locale).format(
", ".join(app.config["submission"]["mime_types"]), quote=True ", ".join(app.config["submission"]["mime_types"]), quote=True
), ),
quote=True, quote=True,
@ -239,7 +240,7 @@ async def get_submission(app: PyroClient, msg: Message):
except SubmissionDuplicatesError as exp: except SubmissionDuplicatesError as exp:
await msg.reply_text( await msg.reply_text(
app._( app._(
"sub_media_duplicates_list", "message", locale=user_locale "sub_media_duplicates_list", "message", locale=user.locale
).format("\n".join(exp.duplicates)), ).format("\n".join(exp.duplicates)),
quote=True, quote=True,
) )
@ -254,7 +255,7 @@ async def get_submission(app: PyroClient, msg: Message):
try: try:
submitted = await app.submit_photo(str(inserted.inserted_id)) submitted = await app.submit_photo(str(inserted.inserted_id))
await msg.reply_text( await msg.reply_text(
app._("sub_yes_auto", "message", locale=user_locale), app._("sub_yes_auto", "message", locale=user.locale),
disable_notification=True, disable_notification=True,
quote=True, quote=True,
) )
@ -264,22 +265,22 @@ async def get_submission(app: PyroClient, msg: Message):
return return
except SubmissionUnsupportedError: except SubmissionUnsupportedError:
await msg.reply_text( await msg.reply_text(
app._("mime_not_allowed", "message", locale=user_locale).format( app._("mime_not_allowed", "message", locale=user.locale).format(
", ".join(app.config["submission"]["mime_types"]), quote=True ", ".join(app.config["submission"]["mime_types"]), quote=True
) )
) )
return return
except SubmissionDuplicatesError as exp: except SubmissionDuplicatesError as exp:
await msg.reply_text( await msg.reply_text(
app._("sub_dup", "message", locale=user_locale), quote=True app._("sub_dup", "message", locale=user.locale), quote=True
) )
return return
except Exception as exp: except Exception as exp:
await app.send_message( await app.send_message(
app.owner, app.owner,
app._("sub_error_admin", "message").format( app._(
msg.from_user.id, format_exc() "sub_error_admin", "message", locale=user_owner.locale
), ).format(msg.from_user.id, format_exc()),
) )
await msg.reply_text("sub_error", quote=True) await msg.reply_text("sub_error", quote=True)
return return
@ -288,17 +289,17 @@ async def get_submission(app: PyroClient, msg: Message):
buttons += [ buttons += [
[ [
InlineKeyboardButton( InlineKeyboardButton(
text=app._("sub_block", "button"), text=app._("sub_block", "button", locale=user_owner.locale),
callback_data=f"sub_block_{msg.from_user.id}", callback_data=f"sub_block_{msg.from_user.id}",
) )
] ]
] ]
PosterUser(msg.from_user.id).limit() await user.update_cooldown()
if msg.from_user.id != app.owner: if msg.from_user.id != app.owner:
await msg.reply_text( await msg.reply_text(
app._("sub_sent", "message", locale=user_locale), app._("sub_sent", "message", locale=user.locale),
disable_notification=True, disable_notification=True,
quote=True, quote=True,
) )

42
plugins/language.py Normal file
View File

@ -0,0 +1,42 @@
from pykeyboard import InlineButton, InlineKeyboard
from pyrogram import filters
from pyrogram.client import Client
from pyrogram.types import CallbackQuery, Message
from classes.pyroclient import PyroClient
@Client.on_message(
~filters.scheduled & filters.private & filters.command(["language"], prefixes=["/"]) # type: ignore
)
async def command_language(app: PyroClient, message: Message):
user = await app.find_user(message.from_user)
keyboard = InlineKeyboard(row_width=2)
buttons = []
for locale, data in app.in_every_locale("metadata").items():
buttons.append(
InlineButton(f"{data['flag']} {data['name']}", f"language:{locale}")
)
keyboard.add(*buttons)
await message.reply_text(
app._("locale_choice", "messages", locale=user.locale),
reply_markup=keyboard,
)
@Client.on_callback_query(filters.regex(r"language:[\s\S]*")) # type: ignore
async def callback_language(app: PyroClient, callback: CallbackQuery):
user = await app.find_user(callback.from_user)
language = str(callback.data).split(":")[1]
await user.update_locale(language)
await callback.answer(
app._("locale_set", "callbacks", locale=language).format(
locale=app._("name", "metadata", locale=language)
),
show_alert=True,
)