Skip to content

Commit

Permalink
Fix localization
Browse files Browse the repository at this point in the history
  • Loading branch information
nazar220160 committed Dec 7, 2023
1 parent 1d1300e commit 99ba892
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 61 deletions.
5 changes: 3 additions & 2 deletions src/bot/common/middlewares/ban.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from src.bot.utils import texts
from src.config.settings import Settings
from src.database.core import Database
from src.bot.common.middlewares.i18n import gettext as _


class BanMiddleware(BaseMiddleware):
Expand All @@ -32,6 +33,6 @@ async def __call__(
return result

if isinstance(event, types.Message):
await event.reply(text=texts.USER_BLOCKED)
await event.reply(text=_(texts.USER_BLOCKED))
if isinstance(event, types.CallbackQuery):
await event.answer(text=texts.USER_BLOCKED_ALERT, show_alert=True)
await event.answer(text=_(texts.USER_BLOCKED_ALERT), show_alert=True)
2 changes: 1 addition & 1 deletion src/bot/common/middlewares/throttle.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ async def __call__(
count = int(is_throttled.decode())
if count == TRIGGER_VALUE:
await self._storage.redis.set(name=user, value=count + 1, ex=timeout) # type: ignore
return await event.answer(texts.THROTTLED) # type: ignore
return await event.answer(_(texts.THROTTLED)) # type: ignore
elif count > TRIGGER_VALUE:
return
else:
Expand Down
43 changes: 22 additions & 21 deletions src/bot/keyboards/inline.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from src.bot.utils.other import get_next_pag

from src.bot.utils.texts import buttons as texts
from src.bot.common.middlewares.i18n import gettext as _


def start():
Expand All @@ -15,11 +16,11 @@ def start():

def admin():
result = InlineKeyboardBuilder()
result.row(InlineKeyboardButton(text=f"📢 {texts.NEWSLETTER}", callback_data=Cd.Admin.ross()))
result.add(InlineKeyboardButton(text=f"👥 {texts.ADMINS}", callback_data=Cd.Admin.get_admins()))
result.row(InlineKeyboardButton(text=f"💭 {texts.COM_SUB}", callback_data=Cd.Admin.com_sub()))
result.row(InlineKeyboardButton(text=f"🚫 {texts.BANNED_USERS}", callback_data=Cd.Admin.banned_users()))
result.row(InlineKeyboardButton(text=f"🔙 {texts.BACK}", callback_data=Cd.Back.main_menu()))
result.row(InlineKeyboardButton(text=f"📢 {_(texts.NEWSLETTER)}", callback_data=Cd.Admin.ross()))
result.add(InlineKeyboardButton(text=f"👥 {_(texts.ADMINS)}", callback_data=Cd.Admin.get_admins()))
result.row(InlineKeyboardButton(text=f"💭 {_(texts.COM_SUB)}", callback_data=Cd.Admin.com_sub()))
result.row(InlineKeyboardButton(text=f"🚫 {_(texts.BANNED_USERS)}", callback_data=Cd.Admin.banned_users()))
result.row(InlineKeyboardButton(text=f"🔙 {_(texts.BACK)}", callback_data=Cd.Back.main_menu()))
return result.as_markup()


Expand All @@ -29,7 +30,7 @@ def admin_list(ls: list[list[UserDTO]], page_num=0):
count = page_num if len_ls != 1 else 0
for i in ls[count]:
result.row(InlineKeyboardButton(text=i.full_name, callback_data='None'))
result.add(InlineKeyboardButton(text=f"✂️ {texts.DELETE}", callback_data=Cd.Admin.remove_admin(i.user_id)))
result.add(InlineKeyboardButton(text=f"✂️ {_(texts.DELETE)}", callback_data=Cd.Admin.remove_admin(i.user_id)))
if len(ls) != 1:
move_back, move_next = get_next_pag(len_ls=len_ls, page_num=page_num)

Expand All @@ -40,7 +41,7 @@ def admin_list(ls: list[list[UserDTO]], page_num=0):
result.add(InlineKeyboardButton(text=f"{page_num + 1}/{len_ls}", callback_data=f"None"))
result.add(InlineKeyboardButton(text=f"➡", callback_data=callback_data_next))

result.row(InlineKeyboardButton(text=f"🔙 {texts.BACK}", callback_data=Cd.Admin.main()))
result.row(InlineKeyboardButton(text=f"🔙 {_(texts.BACK)}", callback_data=Cd.Admin.main()))
return result.as_markup()


Expand All @@ -52,7 +53,7 @@ def com_chats(ls: list[list[ComSubChatsDTO]], page_num=0):
cb_turn = Cd.Admin.com_chat_toggle_turn(i.chat_id)
result.row(InlineKeyboardButton(text="🟢" if i.turn else "🔴", callback_data=cb_turn))
result.add(InlineKeyboardButton(text=i.username, callback_data='None'))
result.add(InlineKeyboardButton(text=f"✂️ {texts.DELETE}", callback_data=Cd.Admin.remove_com_chat(i.chat_id)))
result.add(InlineKeyboardButton(text=f"✂️ {_(texts.DELETE)}", callback_data=Cd.Admin.remove_com_chat(i.chat_id)))
if len(ls) != 1:
move_back, move_next = get_next_pag(len_ls=len_ls, page_num=page_num)

Expand All @@ -63,25 +64,25 @@ def com_chats(ls: list[list[ComSubChatsDTO]], page_num=0):
result.add(InlineKeyboardButton(text=f"{page_num + 1}/{len_ls}", callback_data=f"None"))
result.add(InlineKeyboardButton(text=f"➡", callback_data=callback_data_next))

result.row(InlineKeyboardButton(text=f"➕ {texts.ADD}", callback_data=Cd.Admin.add_com_chat()))
result.add(InlineKeyboardButton(text=f"🔙 {texts.BACK}", callback_data=Cd.Admin.main()))
result.row(InlineKeyboardButton(text=f"➕ {_(texts.ADD)}", callback_data=Cd.Admin.add_com_chat()))
result.add(InlineKeyboardButton(text=f"🔙 {_(texts.BACK)}", callback_data=Cd.Admin.main()))
return result.as_markup()


def confirm_ross():
result = InlineKeyboardBuilder()
confirm = InlineKeyboardButton(text=f"✅ {texts.CONFIRM}", callback_data=Cd.Admin.confirm_ross())
cancel = InlineKeyboardButton(text=f"❌ {texts.CANCEL}", callback_data=Cd.Admin.main())
confirm = InlineKeyboardButton(text=f"✅ {_(texts.CONFIRM)}", callback_data=Cd.Admin.confirm_ross())
cancel = InlineKeyboardButton(text=f"❌ {_(texts.CANCEL)}", callback_data=Cd.Admin.main())
result.row(confirm).add(cancel)
return result.as_markup()


def back(to, main_menu: bool = False, cancel: bool = False):
text = f"🔙 {texts.BACK}"
text = f"🔙 {_(texts.BACK)}"
if cancel is True:
text = f"❌ {texts.CANCEL}"
text = f"❌ {_(texts.CANCEL)}"
if main_menu is True:
text = f"🔙 {texts.MAIN_MENU}"
text = f"🔙 {_(texts.MAIN_MENU)}"
result = InlineKeyboardBuilder()
result.add(InlineKeyboardButton(text=text, callback_data=to))
return result.as_markup()
Expand All @@ -98,11 +99,11 @@ def subscribe_chats(chat_list: List[ComSubChatsDTO]):
def add_com_chat(bot_username: str):
result = InlineKeyboardBuilder()
url = 'http://t.me/{username}?{command}&admin=change_info+post_messages+edit_messages+delete_messages+restrict_members+invite_users+pin_messages+promote_members+manage_video_chats+anonymous+manage_chat'
result.row(InlineKeyboardButton(text=f"➕ {texts.ADD_TO_CHANNEL}",
result.row(InlineKeyboardButton(text=f"➕ {_(texts.ADD_TO_CHANNEL)}",
url=url.format(username=bot_username, command='startchannel')))
result.add(InlineKeyboardButton(text=f"➕ {texts.ADD_TO_GROUP}",
result.add(InlineKeyboardButton(text=f"➕ {_(texts.ADD_TO_GROUP)}",
url=url.format(username=bot_username, command='startgroup')))
result.row(InlineKeyboardButton(text=f"🔙 {texts.BACK}", callback_data=Cd.Admin.com_sub()))
result.row(InlineKeyboardButton(text=f"🔙 {_(texts.BACK)}", callback_data=Cd.Admin.com_sub()))
return result.as_markup()


Expand All @@ -112,7 +113,7 @@ def banned_users(ls: list[list[UserDTO]], page_num=0):
count = page_num if len_ls != 1 else 0
for i in ls[count]:
result.row(InlineKeyboardButton(text=i.full_name, callback_data='None'))
result.add(InlineKeyboardButton(text=f"✂️ {texts.UNBAN}", callback_data=Cd.Admin.unban(i.user_id)))
result.add(InlineKeyboardButton(text=f"✂️ {_(texts.UNBAN)}", callback_data=Cd.Admin.unban(i.user_id)))
if len(ls) != 1:
move_back, move_next = get_next_pag(len_ls=len_ls, page_num=page_num)

Expand All @@ -123,6 +124,6 @@ def banned_users(ls: list[list[UserDTO]], page_num=0):
result.add(InlineKeyboardButton(text=f"{page_num + 1}/{len_ls}", callback_data=f"None"))
result.add(InlineKeyboardButton(text=f"➡", callback_data=callback_data_next))

result.row(InlineKeyboardButton(text=f"➕ {texts.ADD}", callback_data=Cd.Admin.ban()))
result.add(InlineKeyboardButton(text=f"🔙 {texts.BACK}", callback_data=Cd.Admin.main()))
result.row(InlineKeyboardButton(text=f"➕ {_(texts.ADD)}", callback_data=Cd.Admin.ban()))
result.add(InlineKeyboardButton(text=f"🔙 {_(texts.BACK)}", callback_data=Cd.Admin.main()))
return result.as_markup()
65 changes: 33 additions & 32 deletions src/bot/routers/admin/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@
from src.bot.utils.callback import CallbackData as Cb
from src.bot.utils.other import paginate
from src.utils.enums import Status
from src.bot.common.middlewares.i18n import gettext as _


@admin_router.message(Command('admin'), IsAdmin())
async def start(message: types.Message, db: Database):
all_users = await db.user.select_many()
await message.answer(texts.START.format(len_users=len(all_users)),
await message.answer(_(texts.START).format(len_users=len(all_users)),
reply_markup=keyboards.admin())


Expand All @@ -35,13 +36,13 @@ async def admin_callback(callback: types.CallbackQuery, state: FSMContext, bot:
if data.data == Cb.Admin.ross():
await state.set_state(Newsletter.message)
await state.set_data({'message_id': callback.message.message_id})
await callback.message.edit_text(texts.ENTER_MESSAGE_FOR_ROSS,
await callback.message.edit_text(_(texts.ENTER_MESSAGE_FOR_ROSS),
reply_markup=keyboards.back(to=Cb.Admin.main()))
elif data.data == Cb.Admin.main():
await state.clear()
await callback.message.delete()
all_users = await db.user.select_many()
await callback.message.answer(texts.START.format(len_users=len(all_users)),
await callback.message.answer(_(texts.START).format(len_users=len(all_users)),
reply_markup=keyboards.admin())
elif data.data == Cb.Admin.confirm_ross():
list_users = await db.user.select_many()
Expand All @@ -56,15 +57,15 @@ async def admin_callback(callback: types.CallbackQuery, state: FSMContext, bot:
await callback.message.delete()
list_chats = await db.com_sub_chats.select_many()
pag = paginate(list_items=list_chats, items_per_page=5)
await callback.message.answer(text=texts.ADMIN_PANEL_COM_SUB,
await callback.message.answer(text=_(texts.ADMIN_PANEL_COM_SUB),
reply_markup=keyboards.com_chats(ls=pag))

elif data.data == Cb.Admin.add_com_chat():
await callback.message.delete()
await state.set_state(ComChatCreator.chat_id)
bot_info = await bot.me()
reply_markup = keyboards.add_com_chat(bot_username=bot_info.username)
await callback.message.answer(texts.ADD_COM_CHAT, reply_markup=reply_markup)
await callback.message.answer(_(texts.ADD_COM_CHAT), reply_markup=reply_markup)

elif data.data == Cb.Admin.remove_com_chat():
chat_id = int(data.args[0])
Expand Down Expand Up @@ -97,7 +98,7 @@ async def admin_callback(callback: types.CallbackQuery, state: FSMContext, bot:

elif data.data == Cb.Admin.remove_admin():
if callback.from_user.id not in settings.admins:
await callback.answer(text=texts.INSUFFICIENT_PERMISSIONS, show_alert=True)
await callback.answer(text=_(texts.INSUFFICIENT_PERMISSIONS), show_alert=True)
return

await db.user.update(user_id=int(data.args[0]), query=UserUpdate(admin=False))
Expand All @@ -119,7 +120,7 @@ async def admin_callback(callback: types.CallbackQuery, state: FSMContext, bot:
pag = paginate(list_items=list_banned_users, items_per_page=5)
await callback.message.delete()
await callback.message.answer(
text=texts.BANNED_USERS,
text=_(texts.BANNED_USERS),
reply_markup=keyboards.banned_users(ls=pag)
)

Expand All @@ -141,12 +142,12 @@ async def admin_callback(callback: types.CallbackQuery, state: FSMContext, bot:
pag = paginate(list_items=list_banned_users, items_per_page=5)
reply_markup = keyboards.banned_users(ls=pag)
await callback.message.edit_reply_markup(reply_markup=reply_markup)
await callback.answer(text=texts.SUCCESSFUL)
await callback.answer(text=_(texts.SUCCESSFUL))

elif data.data == Cb.Admin.ban():
await callback.message.delete()
await callback.message.answer(
text=texts.SEND_USER_ID_TO_BAN,
text=_(texts.SEND_USER_ID_TO_BAN),
reply_markup=keyboards.back(to=Cb.Admin.main(), cancel=True)
)
await state.set_state(BanUser.user_id)
Expand All @@ -156,13 +157,13 @@ async def admin_callback(callback: types.CallbackQuery, state: FSMContext, bot:
async def get_user_id_ban_user(message: types.Message, db: Database, state: FSMContext):
check_user = await db.user.select(user_id=message.text)
if not check_user:
await message.reply(texts.USER_NOT_FOUND, reply_markup=keyboards.back(to=Cb.Admin.main(), cancel=True))
await message.reply(_(texts.USER_NOT_FOUND), reply_markup=keyboards.back(to=Cb.Admin.main(), cancel=True))
return

await db.user.update(user_id=message.text, query=UserUpdate(
blocked=True
))
await message.reply(text=texts.BAN_USER_SUCCESSFUL.format(check_user.first_name),
await message.reply(text=_(texts.BAN_USER_SUCCESSFUL).format(check_user.first_name),
reply_markup=keyboards.back(to=Cb.Admin.main(), main_menu=True))
await state.clear()

Expand All @@ -176,19 +177,19 @@ async def ross(message: types.Message, user_id: int, list_users: List[UserDTO]):
continue
try:
await message.copy_to(chat_id=i.user_id)
file_text += bytes(f"{i.user_id}: {texts.SUCCESSFUL}\n", 'utf-8')
file_text += bytes(f"{i.user_id}: {_(texts.SUCCESSFUL)}\n", 'utf-8')
good += 1
except Exception as e:
errors.append(e)
file_text += bytes(f"{i.user_id}: {texts.ERROR} - {e}\n", 'utf-8')
file_text += bytes(f"{i.user_id}: {_(texts.ERROR)} - {e}\n", 'utf-8')
text_file = types.input_file.BufferedInputFile(file=file_text,
filename=texts.ROSS_FILE_NAME.format(
filename=_(texts.ROSS_FILE_NAME).format(
date=datetime.now().date()))

await message.edit_reply_markup()
if file_text:
await message.reply_document(document=text_file,
caption=texts.ROSS_DONE.format(good=good, errors=len(errors)),
caption=_(texts.ROSS_DONE).format(good=good, errors=len(errors)),
reply_markup=keyboards.back(to=Cb.Admin.main()))


Expand All @@ -205,15 +206,15 @@ async def get_ross_message(message: types.Message, state: FSMContext, bot: MyBot
async def add_admin(message: types.Message, db: Database):
message_args = message.text.split()
if len(message_args) < 2:
await message.answer(texts.FOR_SEND_MESSAGE_ENTER_COMMAND)
await message.answer(_(texts.FOR_SEND_MESSAGE_ENTER_COMMAND))

else:
try:
user_id = int(message_args[1])
await db.user.update(user_id=user_id, query=UserUpdate(admin=True))
await message.answer(texts.SUCCESSFUL)
await message.answer(_(texts.SUCCESSFUL))
except ValueError:
await message.answer(texts.MUST_BE_INTEGER)
await message.answer(_(texts.MUST_BE_INTEGER))


@admin_router.message(F.reply_to_message, IsAdmin())
Expand All @@ -222,26 +223,26 @@ async def answer_the_question(message: types.Message, db: Database):

database_message = await db.question.select(admin_message_id=message_id)
if database_message is None:
await message.reply(texts.MESSAGE_NOT_FOUND)
await message.reply(_(texts.MESSAGE_NOT_FOUND))
return
if database_message.status == Status.SUCCESS:
await message.reply(texts.MESSAGE_ALREADY_ANSWERED)
await message.reply(_(texts.MESSAGE_ALREADY_ANSWERED))
return
elif database_message.status == Status.IN_PROGRESS:
await message.reply(texts.MESSAGE_ALREADY_ANSWERED)
await message.reply(_(texts.MESSAGE_ALREADY_ANSWERED))
return
try:
await message.send_copy(chat_id=message.reply_to_message.forward_from.id,
reply_to_message_id=database_message.user_message_id)
except TelegramBadRequest:
await message.reply(texts.USER_BLOCKED_BOT_OR_DELETE_MESSAGE)
await message.reply(_(texts.USER_BLOCKED_BOT_OR_DELETE_MESSAGE))
return
except AttributeError:
await message.reply(texts.ERROR)
await message.reply(_(texts.ERROR))
return

await db.question.update(admin_message_id=message_id, query=QuestionUpdate(answered=True))
await message.reply(texts.REPLY_SEND)
await message.reply(_(texts.REPLY_SEND))


@admin_router.message(ComChatCreator.chat_id, IsAdmin())
Expand All @@ -251,32 +252,32 @@ async def get_com_chat(message: types.Message, bot: MyBot, db: Database, state:
try:
chat_id = int(message.text)
except ValueError:
await message.answer(texts.MUST_BE_INTEGER, reply_markup=back_kb)
await message.answer(_(texts.MUST_BE_INTEGER), reply_markup=back_kb)
return
elif message.forward_from:
await message.answer(texts.MESSAGE_MUST_BE_FORWARD_FROM_CHANNEL, reply_markup=back_kb)
await message.answer(_(texts.MESSAGE_MUST_BE_FORWARD_FROM_CHANNEL), reply_markup=back_kb)
return
elif message.forward_from_chat:
chat_id = message.forward_from_chat.id
else:
await message.answer(texts.UNKNOWN_ERROR, reply_markup=back_kb)
await message.answer(_(texts.UNKNOWN_ERROR), reply_markup=back_kb)
return

try:
bot_info = await bot.me()
chat_info = await bot.get_chat(chat_id=chat_id)
if chat_info.username is None:
await message.answer(texts.GET_COM_CHAT_MUST_BE_PUBLIC, reply_markup=back_kb)
await message.answer(_(texts.GET_COM_CHAT_MUST_BE_PUBLIC), reply_markup=back_kb)
return

chat_db = await db.com_sub_chats.select(chat_id=chat_info.id)
if chat_db is not None:
await message.answer(texts.GET_COM_CHAT_ALREADY_IN_DB, reply_markup=back_kb)
await message.answer(_(texts.GET_COM_CHAT_ALREADY_IN_DB), reply_markup=back_kb)
return

bot_in_chat = await bot.get_chat_member(user_id=bot_info.id, chat_id=chat_id)
if bot_in_chat.status != ChatMemberStatus.ADMINISTRATOR:
await message.answer(texts.GET_COM_CHAT_NOT_ADMIN, reply_markup=back_kb)
await message.answer(_(texts.GET_COM_CHAT_NOT_ADMIN), reply_markup=back_kb)
return

await db.com_sub_chats.create(query=ComSubChatsCreate(
Expand All @@ -289,11 +290,11 @@ async def get_com_chat(message: types.Message, bot: MyBot, db: Database, state:
list_chats = await db.com_sub_chats.select_many()
pag = paginate(list_items=list_chats, items_per_page=5)
all_users = await db.user.select_many()
await message.answer(text=texts.START.format(len_users=len(all_users)),
await message.answer(text=_(texts.START).format(len_users=len(all_users)),
reply_markup=keyboards.com_chats(ls=pag))

except TelegramBadRequest:
await message.answer(text=texts.GET_COM_CHAT_NOT_FOUND, reply_markup=back_kb)
await message.answer(text=_(texts.GET_COM_CHAT_NOT_FOUND), reply_markup=back_kb)
return


Expand Down
Loading

0 comments on commit 99ba892

Please sign in to comment.