This commit is contained in:
tema 2022-06-05 15:02:41 +03:00
parent 64c6aeb002
commit 7abdf589aa
Signed by: tema
GPG Key ID: 21FDB6D162488F6F
43 changed files with 164 additions and 135 deletions

View File

@ -3,10 +3,10 @@
token = "123:adminadmin" token = "123:adminadmin"
skip_update = False # skip_update = True #
use_webhook = True # use_webhook = False #
#telegram_api_server = "" # #telegram_api_server = "" #
#permission_file = "" #permission_file = "" #
app_host = "127.0.0.1" app_host = "127.0.0.1"
app_port = 2001 app_port = 2001

View File

@ -1,6 +1,8 @@
from load import dp from load import dp
from .admin import IsAdmin from .admin import IsAdmin
from .operator import IsOperator
dp.filters_factory.bind(IsAdmin) dp.filters_factory.bind(IsAdmin)
dp.filters_factory.bind(IsOperator)

View File

@ -1,3 +1,4 @@
from . import user from . import user
from . import admin from . import admin
from . import callback from . import callback
from . import operator

View File

@ -1,15 +1,13 @@
import io
from aiogram import types from aiogram import types
from aiogram.types import ContentType
from aiogram.dispatcher import FSMContext from aiogram.dispatcher import FSMContext
from aiogram.types import ContentType
from load import bot, dp, messages
from utils.helper import download_file
from keyboard.default.admin.main_menu import base_menu, continue_btn, all_right from keyboard.default.admin.main_menu import base_menu, continue_btn, all_right
from keyboard.default.main_menu import back_to_main_menu from keyboard.default.main_menu import back_to_main_menu
from load import bot, dp, messages
from state.post import Post from state.post import Post
from utils.database.market import add_item from utils.database.market import add_item
from utils.helper import download_file
@dp.message_handler(lambda x: x.text == messages.add_post, is_admin=True) @dp.message_handler(lambda x: x.text == messages.add_post, is_admin=True)
@ -37,7 +35,7 @@ async def admin_form_desk(message: types.Message, state: FSMContext):
@dp.message_handler(is_admin=True, state=Post.price) @dp.message_handler(is_admin=True, state=Post.price)
async def admin_form_price(message: types.message, state: FSMContext): async def admin_form_price(message: types.message, state: FSMContext):
if not message.text.replace('.','').replace(',', '').isdigit(): if not message.text.replace('.', '').replace(',', '').isdigit():
await Post.price.set() await Post.price.set()
await state.update_data(price=float(message.text.replace(",", "."))) await state.update_data(price=float(message.text.replace(",", ".")))
await bot.send_message(message.chat.id, "Отправьте фото товара") await bot.send_message(message.chat.id, "Отправьте фото товара")
@ -45,7 +43,7 @@ async def admin_form_price(message: types.message, state: FSMContext):
@dp.message_handler(is_admin=True, state=Post.image, content_types=[ContentType.PHOTO]) @dp.message_handler(is_admin=True, state=Post.image, content_types=[ContentType.PHOTO])
async def admin_form_image(message:types.Message, state: FSMContext): async def admin_form_image(message: types.Message, state: FSMContext):
file_id = message.photo[-1].file_id file_id = message.photo[-1].file_id
file_info = await bot.get_file(file_id) file_info = await bot.get_file(file_id)
photo = await download_file(file_info.file_path) photo = await download_file(file_info.file_path)
@ -55,10 +53,10 @@ async def admin_form_image(message:types.Message, state: FSMContext):
"Все данные для поста были заполнены", "Все данные для поста были заполнены",
reply_markup=continue_btn reply_markup=continue_btn
) )
await Post.finish.set() await state.set_state("finish_post")
@dp.message_handler(lambda x:x.text == messages.continue_, state=Post.finish, is_admin=True) @dp.message_handler(lambda x: x.text == messages.continue_, state="finish_post", is_admin=True)
async def finish(message: types.Message, state: FSMContext): async def finish(message: types.Message, state: FSMContext):
data = await state.get_data() data = await state.get_data()
await bot.send_photo( await bot.send_photo(
@ -73,7 +71,8 @@ async def finish(message: types.Message, state: FSMContext):
parse_mode='Markdown' parse_mode='Markdown'
) )
@dp.message_handler(lambda x: x.text == messages.all_right_message, is_admin=True, state=Post.finish)
@dp.message_handler(lambda x: x.text == messages.all_right_message, is_admin=True, state="finish_post")
async def write_on_db(message: types.Message, state: FSMContext): async def write_on_db(message: types.Message, state: FSMContext):
data = await state.get_data() data = await state.get_data()
add_item(**data) add_item(**data)

View File

@ -7,4 +7,3 @@ from keyboard.default.admin.main_menu import main_menu
@dp.message_handler(lambda x: x.text == messages.admin_panel, is_admin=True) @dp.message_handler(lambda x: x.text == messages.admin_panel, is_admin=True)
async def cmd_menu(message: types.Message): async def cmd_menu(message: types.Message):
await bot.send_message(message.chat.id, "Admin panel", reply_markup=main_menu()) await bot.send_message(message.chat.id, "Admin panel", reply_markup=main_menu())

View File

@ -7,13 +7,12 @@ from keyboard.default.admin.main_menu import base_menu
from keyboard.default.main_menu import back_to_main_menu from keyboard.default.main_menu import back_to_main_menu
@dp.message_handler(lambda x: x.text == messages.add_admin, is_admin=True) @dp.message_handler(lambda x: x.text == messages.add_admin, is_admin=True)
async def add_admin(message: types.Message): async def add_admin(message: types.Message):
await bot.send_message( await bot.send_message(
message.chat.id, message.chat.id,
("Отправьте user_id пользователя\n" ("Отправьте user_id пользователя\n"
"Его можно узнать зайдя в информацию о пользователе"), "Его можно узнать зайдя в информацию о пользователе"),
reply_markup=base_menu() reply_markup=base_menu()
) )
await AddUser.user_id.set() await AddUser.user_id.set()
@ -34,4 +33,3 @@ async def add_admin1(message: types.Message, state):
return return
Register.register_admin(user) Register.register_admin(user)
await bot.send_message(message.chat.id, "Администратор добавлен!", reply_markup=back_to_main_menu) await bot.send_message(message.chat.id, "Администратор добавлен!", reply_markup=back_to_main_menu)

View File

@ -4,7 +4,8 @@ from load import dp, bot, messages
from keyboard.inline.admin.user import item_list from keyboard.inline.admin.user import item_list
from utils.database.base import get_full_admin from utils.database.base import get_full_admin
@dp.message_handler(lambda x: x.text==messages.del_admin, is_admin=True)
@dp.message_handler(lambda x: x.text == messages.del_admin, is_admin=True)
async def del_admin(message: types.Message): async def del_admin(message: types.Message):
admins = get_full_admin() admins = get_full_admin()
admin = admins[0] admin = admins[0]
@ -13,5 +14,5 @@ async def del_admin(message: types.Message):
message.chat.id, message.chat.id,
result, result,
parse_mode="Markdown", parse_mode="Markdown",
reply_markup=item_list(items=len(admins)-1) reply_markup=item_list(items=len(admins) - 1)
) )

View File

@ -2,3 +2,4 @@ from . import null
from . import catalog from . import catalog
from . import cart from . import cart
from . import admin from . import admin
from . import operator

View File

@ -25,9 +25,10 @@ async def next_item_adm(callback: types.CallbackQuery):
), ),
parse_mode="Markdown", parse_mode="Markdown",
), ),
reply_markup=item_list(count, len(items)-1, int(data[2])) reply_markup=item_list(count, len(items) - 1, int(data[2]))
) )
@dp.callback_query_handler(lambda c: c.data.split("|")[0] == 'delete_post', is_admin=True) @dp.callback_query_handler(lambda c: c.data.split("|")[0] == 'delete_post', is_admin=True)
async def delete_post_adm(callback: types.CallbackQuery): async def delete_post_adm(callback: types.CallbackQuery):
data = callback.data.split("|") data = callback.data.split("|")
@ -47,7 +48,7 @@ async def delete_post_adm(callback: types.CallbackQuery):
), ),
parse_mode="Markdown", parse_mode="Markdown",
), ),
reply_markup=item_list(items=len(items)-1) reply_markup=item_list(items=len(items) - 1)
) )
else: else:
await callback.message.delete() await callback.message.delete()

View File

@ -1,4 +1,3 @@
from subprocess import call
from aiogram import types from aiogram import types
from load import dp, messages from load import dp, messages
@ -20,6 +19,7 @@ async def next_item_adm(callback: types.CallbackQuery):
) )
await callback.answer() await callback.answer()
@dp.callback_query_handler(lambda x: x.data.split("|")[0] == "delete_admin") @dp.callback_query_handler(lambda x: x.data.split("|")[0] == "delete_admin")
async def delete_admin(callback: types.CallbackQuery): async def delete_admin(callback: types.CallbackQuery):
data = callback.data.split("|") data = callback.data.split("|")

View File

@ -9,14 +9,15 @@ from keyboard.inline.cart import cart_list
from keyboard.default.main_menu import back_to_main_menu from keyboard.default.main_menu import back_to_main_menu
@dp.callback_query_handler(lambda c: c.data.split("|")[0]=="add_to_cart") @dp.callback_query_handler(lambda c: c.data.split("|")[0] == "add_to_cart")
async def add_cart(callback: types.CallbackQuery): async def add_cart(callback: types.CallbackQuery):
item_id = callback.data.split("|")[1] item = int(callback.data.split("|")[1])
item_id = Catalog.get_catalog()[item]["id"]
add_to_cart(callback.from_user.id, item_id) add_to_cart(callback.from_user.id, item_id)
await callback.answer("Товар добавлен!") await callback.answer("Товар добавлен!")
@dp.callback_query_handler(lambda c: c.data.split("|")[0]=="del_from_cart") @dp.callback_query_handler(lambda c: c.data.split("|")[0] == "del_from_cart")
async def del_cart(callback: types.CallbackQuery): async def del_cart(callback: types.CallbackQuery):
c = callback.data.split("|")[1] c = callback.data.split("|")[1]
item_id = get_user_cart(callback.from_user.id)[int(c)][0] item_id = get_user_cart(callback.from_user.id)[int(c)][0]
@ -26,7 +27,7 @@ async def del_cart(callback: types.CallbackQuery):
items = get_user_cart(callback.from_user.id) items = get_user_cart(callback.from_user.id)
if items: if items:
index, count =items[0] index, count = items[0]
item = Catalog.get_catalog(index) item = Catalog.get_catalog(index)
await callback.message.edit_media( await callback.message.edit_media(
media=types.InputMediaPhoto( media=types.InputMediaPhoto(
@ -35,11 +36,11 @@ async def del_cart(callback: types.CallbackQuery):
name=item["name"], name=item["name"],
description=item["description"], description=item["description"],
count=count, count=count,
price=item['price']*count price=item['price'] * count
), ),
parse_mode="Markdown", parse_mode="Markdown",
), ),
reply_markup=cart_list(items=len(items)-1) reply_markup=cart_list(items=len(items) - 1)
) )
else: else:
await callback.message.delete() await callback.message.delete()
@ -66,9 +67,9 @@ async def next_item(callback: types.CallbackQuery):
name=item["name"], name=item["name"],
description=item["description"], description=item["description"],
count=count, count=count,
price=item['price']*count price=item['price'] * count
), ),
parse_mode="Markdown", parse_mode="Markdown",
), ),
reply_markup=cart_list(c, len(items)-1) reply_markup=cart_list(c, len(items) - 1)
) )

View File

@ -26,4 +26,3 @@ async def next_item(callback: types.CallbackQuery):
), ),
reply_markup=item_list(count, len(items)-1, int(data[2])) reply_markup=item_list(count, len(items)-1, int(data[2]))
) )

View File

@ -2,6 +2,7 @@ from aiogram.types import CallbackQuery
from load import dp from load import dp
@dp.callback_query_handler(lambda c: c.data == "null") @dp.callback_query_handler(lambda c: c.data == "null")
async def null(callback: CallbackQuery): async def null(callback: CallbackQuery):
await callback.answer() await callback.answer()

View File

@ -3,3 +3,4 @@ from . import catalog
from . import cart from . import cart
from . import checkout from . import checkout
from . import ordering from . import ordering
from . import support

View File

@ -9,7 +9,7 @@ from state.state import UserState
@dp.message_handler(lambda x: x.text == messages.checkout) @dp.message_handler(lambda x: x.text == messages.checkout)
async def checkout(message:types.Message): async def checkout(message: types.Message):
items = get_user_cart(message.from_user.id) items = get_user_cart(message.from_user.id)
output: str = "" output: str = ""
cost = 0 cost = 0
@ -22,14 +22,14 @@ async def checkout(message:types.Message):
await UserState.confirm.set() await UserState.confirm.set()
@dp.message_handler(lambda x: x.text == messages.all_right_message) @dp.message_handler(lambda x: x.text == messages.all_right_message, state="save_or_continue")
async def continue_user_form(message: types.Message): async def continue_user_form():
pass pass
@dp.message_handler(lambda x: x.text == messages.save_and_continue, state="*") @dp.message_handler(lambda x: x.text == messages.save_and_continue, state="save_or_continue")
async def save_user_info(message: types.Message): async def save_user_info(message: types.Message):
state = dp.current_state(chat=message.chat.id, user=message.from_user.id) state = dp.current_state(chat=message.chat.id, user=message.from_user.id)
info = await state.get_data() info = await state.get_data()
save_info(user_id=message.from_user.id, **info) save_info(user_id=message.from_user.id, **info)
await continue_user_form(message) await continue_user_form()

View File

@ -20,24 +20,23 @@ async def confirm(message: types.Message, state: FSMContext):
"Может у вас есть сохраненные данные?", "Может у вас есть сохраненные данные?",
reply_markup=load_info(bool(info)) reply_markup=load_info(bool(info))
) )
await Checkout.loaded.set() await state.set_state(state="load_data")
@dp.message_handler(lambda x: x.text == messages.load_data, state=Checkout.loaded) @dp.message_handler(lambda x: x.text == messages.load_data, state="load_data")
async def load_form(message: types.message, state: FSMContext): async def load_form(message: types.message, state: FSMContext):
info = get_info(message.from_user.id) info = get_info(message.from_user.id)
await state.update_data( await state.update_data(
loaded=True, first_name=info["first_name"],
first_name = info["first_name"], last_name=info["last_name"],
last_name = info["last_name"], phone_number=info["phone_number"],
phone_number = info["phone_number"], address=info["address"]
address = info["address"]
) )
await bot.send_message(message.chat.id, "Ваши данные загружены!", reply_markup=continue_btn) await bot.send_message(message.chat.id, "Ваши данные загружены!", reply_markup=continue_btn)
await Checkout.finish.set() await state.set_state("finish_send_form")
@dp.message_handler(lambda x: x.text == messages.rewrite_data, state=Checkout.loaded) @dp.message_handler(lambda x: x.text == messages.rewrite_data, state="load_data")
async def new_form(message: types.Message, state: FSMContext = None): async def new_form(message: types.Message, state: FSMContext = None):
await state.update_data(loaded=False) await state.update_data(loaded=False)
await bot.send_message( await bot.send_message(
@ -65,7 +64,7 @@ async def form_first_name(message: types.Message, state: FSMContext):
await bot.send_message( await bot.send_message(
message.chat.id, message.chat.id,
("Номер телефона\n\n" ("Номер телефона\n\n"
"Можете написать номер телефона вручную"), "Можете написать номер телефона вручную"),
reply_markup=get_phone_number reply_markup=get_phone_number
) )
await Checkout.phone_number.set() await Checkout.phone_number.set()
@ -74,35 +73,38 @@ async def form_first_name(message: types.Message, state: FSMContext):
@dp.message_handler(state=Checkout.phone_number, content_types=[types.ContentType.CONTACT, types.ContentType.TEXT]) @dp.message_handler(state=Checkout.phone_number, content_types=[types.ContentType.CONTACT, types.ContentType.TEXT])
async def form_phone(message: types.Message, state: FSMContext): async def form_phone(message: types.Message, state: FSMContext):
if message.contact is not None: if message.contact is not None:
phone=message.contact.phone_number phone = message.contact.phone_number
else: phone=message.text
if len(phone) in [10,12,13]:
await state.update_data(phone_number=phone)
await bot.send_message(message.chat.id, "Отправте адрес доставки", reply_markup=cancel_btn)
await Checkout.address.set()
else: else:
phone = message.text
if len(phone) not in [10, 12, 13]:
await bot.send_message(message.chat.id, "Номер телефона не правильный!") await bot.send_message(message.chat.id, "Номер телефона не правильный!")
await Checkout.phone_number.set() await Checkout.phone_number.set()
return
await state.update_data(phone_number=phone)
await bot.send_message(message.chat.id, "Отправте адрес доставки", reply_markup=cancel_btn)
await Checkout.address.set()
@dp.message_handler(state=Checkout.address) @dp.message_handler(state=Checkout.address)
async def form_address(message: types.Message, state: FSMContext): async def form_address(message: types.Message, state: FSMContext):
await state.update_data(address=message.text) await state.update_data(address=message.text)
await bot.send_message(message.chat.id, "Отлично заявка заполнена!", reply_markup=continue_btn) await bot.send_message(message.chat.id, "Отлично, заявка заполнена!", reply_markup=continue_btn)
await Checkout.finish.set() await state.set_state("finish_send_form")
@dp.message_handler(state=Checkout.finish) @dp.message_handler(state="finish_send_form")
async def finish_form(message: types.Message, state: FSMContext): async def finish_form(message: types.Message, state: FSMContext):
data = await state.get_data() data = await state.get_data()
text = (f"Имя: {data['first_name']}\n" text = (f"Имя: {data['first_name']}\n"
f"Фамилия: {data['last_name']}\n" f"Фамилия: {data['last_name']}\n"
f"Номер телефона: {data['phone_number']}\n" f"Номер телефона: {data['phone_number']}\n"
f"Адрес: {data['address']}\n" f"Адрес: {data['address']}\n"
) )
await bot.send_message( await bot.send_message(
message.chat.id, message.chat.id,
text, text,
reply_markup=confirm_all_info() reply_markup=confirm_all_info()
) )
await state.set_state("save_or_continue")

View File

@ -18,6 +18,7 @@ async def start(message: types.Message):
reply_markup=main_menu(admin=is_bot_admin, operator=is_operator) reply_markup=main_menu(admin=is_bot_admin, operator=is_operator)
) )
@dp.message_handler(lambda x: x.text == messages.back) @dp.message_handler(lambda x: x.text == messages.back)
async def back_to_menu(message: types.Message): async def back_to_menu(message: types.Message):
is_bot_admin = message.from_user.id in get_admins() is_bot_admin = message.from_user.id in get_admins()
@ -36,11 +37,11 @@ async def cancel(message: types.Message):
await back_to_menu(message) await back_to_menu(message)
@dp.message_handler(lambda x:x.text == messages.info) @dp.message_handler(lambda x: x.text == messages.info)
async def userinfo(message: types.Message): async def userinfo(message: types.Message):
await bot.send_message( await bot.send_message(
message.chat.id, message.chat.id,
("User_id: <code>{user_id}</code>").format(user_id=message.from_user.id), "User_id: <code>{user_id}</code>".format(user_id=message.from_user.id),
parse_mode="HTML" parse_mode="HTML"
) )

View File

@ -31,11 +31,11 @@ def base_menu(cancel=True, skip=False):
continue_btn = ReplyKeyboardMarkup( continue_btn = ReplyKeyboardMarkup(
[[KeyboardButton(messages.continue_), [[KeyboardButton(messages.continue_),
KeyboardButton(messages.cancel_message)]], KeyboardButton(messages.cancel_message)]],
resize_keyboard=True resize_keyboard=True
) )
all_right = ReplyKeyboardMarkup( all_right = ReplyKeyboardMarkup(
[[KeyboardButton(messages.all_right_message), [[KeyboardButton(messages.all_right_message),
KeyboardButton(messages.cancel_message)]], KeyboardButton(messages.cancel_message)]],
resize_keyboard=True resize_keyboard=True
) )

View File

@ -2,12 +2,14 @@ from aiogram.types.reply_keyboard import ReplyKeyboardMarkup, KeyboardButton
from load import messages from load import messages
def checkout_btn() -> ReplyKeyboardMarkup: def checkout_btn() -> ReplyKeyboardMarkup:
return ReplyKeyboardMarkup([[ return ReplyKeyboardMarkup([[
KeyboardButton(messages.all_right_message), KeyboardButton(messages.all_right_message),
KeyboardButton(messages.cancel_message) KeyboardButton(messages.cancel_message)
]], resize_keyboard=True) ]], resize_keyboard=True)
def confirm_all_info(): def confirm_all_info():
markup = ReplyKeyboardMarkup(resize_keyboard=True) markup = ReplyKeyboardMarkup(resize_keyboard=True)
markup.add(KeyboardButton(messages.all_right_message)) markup.add(KeyboardButton(messages.all_right_message))

View File

@ -7,16 +7,17 @@ def main_menu(admin=False, operator=False):
markup = ReplyKeyboardMarkup( markup = ReplyKeyboardMarkup(
[ [
[ [
KeyboardButton(messages.catalog), # Go to catalog KeyboardButton(messages.catalog), # Go to catalog
KeyboardButton(messages.cart) # Go to cart KeyboardButton(messages.cart) # Go to cart
] ]
], ],
resize_keyboard=True resize_keyboard=True
).add(KeyboardButton(messages.info)) ).add(KeyboardButton(messages.info))
if admin == True:
if admin:
markup.add(KeyboardButton(messages.admin_panel)) markup.add(KeyboardButton(messages.admin_panel))
if operator == True: if operator:
markup.add(KeyboardButton(messages.operator_panel)) markup.add(KeyboardButton(messages.operator_panel))
return markup return markup
@ -30,7 +31,8 @@ def cart_btn(is_empty=True):
markup.add(KeyboardButton(messages.back)) markup.add(KeyboardButton(messages.back))
return markup return markup
back_to_main_menu = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(messages.back)]],resize_keyboard=True)
back_to_main_menu = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(messages.back)]], resize_keyboard=True)
cancel_btn = ReplyKeyboardMarkup([[KeyboardButton(messages.cancel_message)]], resize_keyboard=True) cancel_btn = ReplyKeyboardMarkup([[KeyboardButton(messages.cancel_message)]], resize_keyboard=True)
get_phone_number = ReplyKeyboardMarkup( get_phone_number = ReplyKeyboardMarkup(
keyboard=[ keyboard=[

View File

@ -2,6 +2,7 @@ from aiogram.types.reply_keyboard import ReplyKeyboardMarkup, KeyboardButton
from load import messages from load import messages
def load_info(data:bool = False): def load_info(data:bool = False):
markup = ReplyKeyboardMarkup(resize_keyboard=True) markup = ReplyKeyboardMarkup(resize_keyboard=True)
if data: if data:

View File

@ -3,22 +3,20 @@ from aiogram.types.inline_keyboard import InlineKeyboardMarkup, InlineKeyboardBu
from load import messages from load import messages
def item_list(item=0, items:int=1, user_count:int=1) -> InlineKeyboardMarkup: def item_list(item: int = 0, items: int = 1, user_count: int = 1) -> InlineKeyboardMarkup:
markup = InlineKeyboardMarkup() markup = InlineKeyboardMarkup()
default = [ default = [
InlineKeyboardButton(user_count, callback_data='null') InlineKeyboardButton(str(user_count), callback_data='null')
] ]
back = ['⬅️', f"adm_prev|{item-1}|{user_count-1}"] back = ['⬅️', f"adm_prev|{item-1}|{user_count-1}"]
next = ['➡️', f"adm_next|{item+1}|{user_count+1}"] next = ['➡️', f"adm_next|{item+1}|{user_count+1}"]
if items < 1 or item >= items: if items < 1 or item >= items:
next = [" ", "null"] next = [" ", "null"]
if item == 0: if item == 0:
back = [" ", "null"] back = [" ", "null"]
default.append(InlineKeyboardButton(next[0], callback_data=next[1])) default.append(InlineKeyboardButton(next[0], callback_data=next[1]))
markup.add(InlineKeyboardButton(back[0], callback_data=back[1]), *default) markup.add(InlineKeyboardButton(back[0], callback_data=back[1]), *default)

View File

@ -1,22 +1,21 @@
from aiogram.types.inline_keyboard import InlineKeyboardButton, InlineKeyboardMarkup from aiogram.types.inline_keyboard import InlineKeyboardButton, InlineKeyboardMarkup
from load import messages from load import messages
def item_list(item=0, items:int=1, user_count:int=1) -> InlineKeyboardMarkup:
def item_list(item: int = 0, items: int = 1, user_count: int = 1) -> InlineKeyboardMarkup:
markup = InlineKeyboardMarkup() markup = InlineKeyboardMarkup()
default = [ default = [
InlineKeyboardButton(user_count, callback_data='null') InlineKeyboardButton(str(user_count), callback_data='null')
] ]
back = ['⬅️', f"admin_prev|{item-1}|{user_count-1}"] back = ['⬅️', f"admin_prev|{item-1}|{user_count-1}"]
next = ['➡️', f"admin_next|{item+1}|{user_count+1}"] next = ['➡️', f"admin_next|{item+1}|{user_count+1}"]
if items < 1 or item >= items: if items < 1 or item >= items:
next = [" ", "null"] next = [" ", "null"]
if item == 0: if item == 0:
back = [" ", "null"] back = [" ", "null"]
default.append(InlineKeyboardButton(next[0], callback_data=next[1])) default.append(InlineKeyboardButton(next[0], callback_data=next[1]))
markup.add(InlineKeyboardButton(back[0], callback_data=back[1]), *default) markup.add(InlineKeyboardButton(back[0], callback_data=back[1]), *default)

View File

@ -2,15 +2,15 @@ from aiogram.types.inline_keyboard import InlineKeyboardMarkup, InlineKeyboardBu
from load import messages from load import messages
def cart_list(item=0, items:int=1) -> InlineKeyboardMarkup:
def cart_list(item:int = 0, items: int = 1) -> InlineKeyboardMarkup:
markup = InlineKeyboardMarkup() markup = InlineKeyboardMarkup()
default = [ default = [
InlineKeyboardButton(item+1, callback_data='null') InlineKeyboardButton(str(item+1), callback_data='null')
] ]
back = ['⬅️', f"cart_prev|{item-1}"] back = ['⬅️', f"cart_prev|{item-1}"]
next = ['➡️', f"cart_next|{item+1}"] next = ['➡️', f"cart_next|{item+1}"]
if items < 1 or item >= items: if items < 1 or item >= items:
next = [" ", "null"] next = [" ", "null"]

View File

@ -3,15 +3,14 @@ from aiogram.types.inline_keyboard import InlineKeyboardMarkup, InlineKeyboardBu
from load import messages from load import messages
def item_list(item=0, items:int=1, user_count:int=1) -> InlineKeyboardMarkup: def item_list(item: int = 0, items: int = 1, user_count: int = 1) -> InlineKeyboardMarkup:
markup = InlineKeyboardMarkup() markup = InlineKeyboardMarkup()
default = [ default = [
InlineKeyboardButton(user_count, callback_data='null') InlineKeyboardButton(str(user_count), callback_data='null')
] ]
back = ['⬅️', f"prev|{item-1}|{user_count-1}"] back = ['⬅️', f"prev|{item-1}|{user_count-1}"]
next = ['➡️', f"next|{item+1}|{user_count+1}"] next = ['➡️', f"next|{item+1}|{user_count+1}"]
if items < 1 or item >= items: if items < 1 or item >= items:
next = [" ", "null"] next = [" ", "null"]

View File

@ -1,15 +1,14 @@
from aiogram.types.inline_keyboard import InlineKeyboardMarkup, InlineKeyboardButton from aiogram.types.inline_keyboard import InlineKeyboardMarkup, InlineKeyboardButton
def cart_list(item=0, items:int=1) -> InlineKeyboardMarkup: def cart_list(item: int = 0, items: int = 1) -> InlineKeyboardMarkup:
markup = InlineKeyboardMarkup() markup = InlineKeyboardMarkup()
default = [ default = [
InlineKeyboardButton(item+1, callback_data='null') InlineKeyboardButton(str(item+1), callback_data='null')
] ]
back = ['⬅️', f"cart_prev|{item-1}"] back = ['⬅️', f"cart_prev|{item-1}"]
next = ['➡️', f"cart_next|{item+1}"] next = ['➡️', f"cart_next|{item+1}"]
if items < 1 or item >= items: if items < 1 or item >= items:
next = [" ", "null"] next = [" ", "null"]

View File

@ -8,8 +8,7 @@ from peewee import SqliteDatabase
from playhouse.db_url import connect from playhouse.db_url import connect
import config import config
from utils import messages # used, do not delete! from utils import messages # used, do not delete!
# Bot init # Bot init
bot = Bot( bot = Bot(
@ -24,6 +23,6 @@ dp = Dispatcher(
storage=storage storage=storage
) )
db:SqliteDatabase = connect(config.db_url) db: SqliteDatabase = connect(config.db_url)
permissions = json.load(open(config.permission_file)) permissions = json.load(open(config.permission_file))

View File

@ -1,11 +1,8 @@
from aiogram.dispatcher.filters.state import StatesGroup, State from aiogram.dispatcher.filters.state import StatesGroup, State
class Checkout(StatesGroup): class Checkout(StatesGroup):
first_name = State() first_name = State()
last_name = State() last_name = State()
phone_number = State() phone_number = State()
address = State() address = State()
loaded = State()
finish = State()

View File

@ -1,9 +1,8 @@
from aiogram.dispatcher.filters.state import StatesGroup, State from aiogram.dispatcher.filters.state import StatesGroup, State
class Post(StatesGroup): class Post(StatesGroup):
name = State() name = State()
description = State() description = State()
price = State() price = State()
image = State() image = State()
finish = State()

View File

@ -1,5 +1,6 @@
from aiogram.dispatcher.filters.state import StatesGroup, State from aiogram.dispatcher.filters.state import StatesGroup, State
class UserState(StatesGroup): class UserState(StatesGroup):
confirm = State() confirm = State()

View File

@ -14,6 +14,7 @@ def get_operator():
users.append(i.user_id) users.append(i.user_id)
return users return users
def get_full_admin(): def get_full_admin():
usr = [] usr = []
for i in Admin.select(): for i in Admin.select():
@ -28,3 +29,10 @@ def get_full_admin():
def del_admin(user_id:int): def del_admin(user_id:int):
Admin.delete().where(Admin.user_id == user_id).execute() Admin.delete().where(Admin.user_id == user_id).execute()
def get_active_operator():
usr = []
for i in Operator.select().where(Operator.active==True):
usr.append(i.user_id)
return usr

View File

@ -16,6 +16,7 @@ def del_from_cart(user_id: int, item_id: int):
def clean_cart(user_id: int): def clean_cart(user_id: int):
Cart.delete().where(Cart.user_id==user_id).execute() Cart.delete().where(Cart.user_id==user_id).execute()
def get_user_cart(user_id:int): def get_user_cart(user_id:int):
cart = [] cart = []
for i in Cart.select().where(Cart.user_id == user_id): for i in Cart.select().where(Cart.user_id == user_id):

View File

@ -1,10 +1,9 @@
from ast import Mod
import typing as t import typing as t
from .model import Catalog as Model from .model import Catalog as Model
class Catalog(): class Catalog:
@staticmethod @staticmethod
def __get_item(item_id: int) -> dict: def __get_item(item_id: int) -> dict:
item = {} item = {}
@ -23,18 +22,17 @@ class Catalog():
return item return item
@classmethod @classmethod
def get_catalog(self, item_id:int = None, get_count:bool = False) -> t.Union[list, dict]: def get_catalog(cls, item_id:int = None, get_count:bool = False) -> t.Union[list, dict]:
if item_id: if item_id:
if get_count: if get_count:
return self.__get_item(item_id), Model.select().count() return cls.__get_item(item_id), Model.select().count()
return self.__get_item(item_id) return cls.__get_item(item_id)
items = [] items = []
for i in Model.select(): for i in Model.select():
items.append(self.__get_item(i.id)) items.append(cls.__get_item(i.id))
return items return items
@staticmethod @staticmethod
def delete_post(item_id: int): def delete_post(item_id: int):
return Model.delete_by_id(item_id) return Model.delete_by_id(item_id)

View File

@ -1,11 +1,11 @@
from peewee import (Model, BigIntegerField, TextField, BlobField, from peewee import (Model, BigIntegerField, TextField, BlobField,
IntegerField, CharField, FloatField, ForeignKeyField) IntegerField, CharField, FloatField, BooleanField)
from load import db from load import db
class BaseModel(Model): class BaseModel(Model):
'''Base model. Abstract Class''' """Base model. Abstract Class"""
class Meta: class Meta:
database = db database = db
@ -22,7 +22,7 @@ class Admin(User):
class Operator(User): class Operator(User):
pass active = BooleanField(default=False)
class Catalog(BaseModel): class Catalog(BaseModel):
@ -45,4 +45,5 @@ class UserInfo(BaseModel):
phone_number = CharField(15) phone_number = CharField(15)
address = TextField() address = TextField()
db.create_tables([Cart, Catalog, Operator, Admin, User, UserInfo]) db.create_tables([Cart, Catalog, Operator, Admin, User, UserInfo])

View File

@ -10,6 +10,7 @@ def save_info(user_id: int, last_name:str, first_name:str, phone_number:str, add
address=address address=address
).on_conflict_replace().execute() ).on_conflict_replace().execute()
def get_info(user_id: int): def get_info(user_id: int):
output = None output = None
if UserInfo.select().where(UserInfo.user_id == user_id).exists(): if UserInfo.select().where(UserInfo.user_id == user_id).exists():

View File

@ -9,7 +9,7 @@ from utils import types
class Register: class Register:
@classmethod @classmethod
def __register_user(self, model: Model, user: UserType): def __register_user(cls, model: Model, user: UserType):
model.insert( model.insert(
user_id=user.id, user_id=user.id,
first_name=user.first_name, first_name=user.first_name,
@ -18,16 +18,16 @@ class Register:
).on_conflict_replace().execute() ).on_conflict_replace().execute()
@classmethod @classmethod
def register_user(self, user: UserType): def register_user(cls, user: UserType):
return self.__register_user(UserModel, user) return cls.__register_user(UserModel, user)
@classmethod @classmethod
def register_admin(self, user: UserType): def register_admin(cls, user: UserType):
return self.__register_user(Admin, user) return cls.__register_user(Admin, user)
@classmethod @classmethod
def register_operator(self, user: UserType): def register_operator(cls, user: UserType):
return self.__register_user(Operator, user) return cls.__register_user(Operator, user)
class User: class User:
@ -43,3 +43,15 @@ class User:
last_name=data.last_name, last_name=data.last_name,
username=data.username username=data.username
) )
@staticmethod
def get_state(user_id:int):
if Operator.select().where(Operator.user_id == user_id).exists():
return Operator.get(Operator.user_id == user_id).active
return False
@staticmethod
def set_state(user_id:int, state:bool=False):
if Operator.select().where(Operator.user_id == user_id).exists():
Operator.update(active=state).where(Operator.user_id == user_id).execute()
return None

View File

@ -3,6 +3,7 @@ import typing as t
from load import bot, config from load import bot, config
async def download_file(file_path, *args, **kw) -> t.Union[io.BytesIO, t.Any]: async def download_file(file_path, *args, **kw) -> t.Union[io.BytesIO, t.Any]:
if config.telegram_api_server == "https://api.telegram.org": if config.telegram_api_server == "https://api.telegram.org":
return await bot.download_file(file_path, *args, **kw) return await bot.download_file(file_path, *args, **kw)

View File

@ -1,5 +1,6 @@
from pydantic import BaseModel from pydantic import BaseModel
class Permission(BaseModel): class Permission(BaseModel):
can_admin_add_admins: bool can_admin_add_admins: bool
can_admin_del_admins: bool can_admin_del_admins: bool

View File

@ -19,6 +19,9 @@ continue_ = "Продолжить"
rewrite_data = "Ввести заново" rewrite_data = "Ввести заново"
load_data = "Загрузить данные" load_data = "Загрузить данные"
#Operator
on_work = "Активировать"
leave_work = "Выключить"
#Admins \ Moder #Admins \ Moder
admin_panel = "Админ панель" admin_panel = "Админ панель"

View File

@ -2,22 +2,22 @@ import typing as t
from abc import ABC from abc import ABC
class BaseUserFileds(ABC): class BaseUser(ABC):
id: int id: int
first_name: str first_name: str
last_name: t.Union[str, None] = None last_name: t.Union[str, None] = None
username: t.Union[str, None] = None username: t.Union[str, None] = None
class User(BaseUserFileds): class User(BaseUser):
def __new__(self, **kw): def __new__(cls, **kw):
if "user_id" in kw: if "user_id" in kw:
self.id = kw["user_id"] cls.id = kw["user_id"]
if "first_name" in kw: if "first_name" in kw:
self.first_name = kw["first_name"] cls.first_name = kw["first_name"]
if "last_name" in kw: if "last_name" in kw:
self.last_name = kw["last_name"] cls.last_name = kw["last_name"]
if "username" in kw: if "username" in kw:
self.username = kw["username"] cls.username = kw["username"]
return self return cls