New features

This commit is contained in:
tema 2022-06-16 00:32:17 +03:00
parent 63afce795e
commit 2b69567cc9
Signed by: tema
GPG Key ID: 21FDB6D162488F6F
31 changed files with 318 additions and 77 deletions

View File

@ -1,25 +1,26 @@
from environs import Env
CONFIG_FILE = '.env'
env = Env()
env.read_env(CONFIG_FILE)
token = env.str("token")
db_url = env.str("database_url", "sqlite:///database.sqlite3")
permission_file = env.str("permission_file", "permission.json")
token: str = env.str("TOKEN")
service_chat: int = env.int("SERVICE_CHAT")
use_webhook = env.bool("use_webhook", False)
skip_updates = env.bool("skip_update", True)
telegram_api_server = env.str("telegram_api_server", "https://api.telegram.org")
db_url: str = env.str("DATABASE_URL", "sqlite:///database.sqlite3")
permission_file: str = env.str("PERMISSION_FILE", "permission.json")
use_webhook: bool = env.bool("USE_WEBHOOK", False)
skip_updates: bool = env.bool("SKIP_UPDATE", True)
telegram_api_server: str = env.str("TELEGRAM_API_SERVER", "https://api.telegram.org")
if use_webhook:
webhook_app_host = env.str("app_host")
webhook_app_port = env.int("app_port")
webhook_app_host: str = env.str("APP_HOST")
webhook_app_port: int = env.int("APP_PORT")
webhook_host = env.str("webhook_host")
webhook_host: str = env.str("WEBHOOK_HOST")
webhook_path = f"/bot{token}"
webhook_url = f"{webhook_host}{webhook_path}"
webhook_path: str = f"/bot{token}"
webhook_url: str = f"{webhook_host}{webhook_path}"

View File

@ -1,16 +1,16 @@
# Установите # в начало строки, чтобы использовать значение по умолчанию
# Строки которые имеют значение по умолчанию позначены # в конце строки
token = "123:adminadmin"
TOKEN="123:adminadmin"
SERVICE_CHAT=0
skip_update = True #
use_webhook = False #
#telegram_api_server = "" #
#permission_file = "" #
SKIP_UPDATE=true#
USE_WEBHOOK=false#
#TELEGRAM_API_SERVER=""#
#PERMISSION_FILE=""#
app_host = "127.0.0.1"
app_port = 2001
webhook_host = "http://127.0.0.1:2001"
APP_HOST="127.0.0.1"
APP_PORT=2001
WEBHOOK_HOST="http://127.0.0.1:2001"
#database_url = "" #
#DATABASE_URL = ""#

View File

@ -1,4 +1,5 @@
from . import panel
from . import add_post
from . import delete_post
from . import user_control
from . import admin_control
from . import operator_control

View File

@ -18,6 +18,14 @@ async def cmd_add_post(message: types.Message):
@dp.message_handler(is_admin=True, state=Post.name)
async def admin_form_name(message: types.Message, state: FSMContext):
if len(message.text) > 50:
await bot.send_message(
message.chat.id,
("Имя не может быть больше 50 символов!\n"
"Повторите попытку")
)
await Post.name.set()
return
await state.update_data(name=message.text)
await bot.send_message(message.chat.id, "Укажите описание товара", reply_markup=base_menu(skip=True))
await Post.description.set()
@ -25,6 +33,15 @@ async def admin_form_name(message: types.Message, state: FSMContext):
@dp.message_handler(is_admin=True, state=Post.description)
async def admin_form_desk(message: types.Message, state: FSMContext):
if len(message.text) > 1000:
await bot.send_message(
message.chat.id,
("Описание не может быть больше 1000 символов!\n"
"Повторите попытку")
)
await Post.description.set()
return
if message.text == messages.skip_message:
await state.update_data(description="")
else:
@ -35,6 +52,15 @@ async def admin_form_desk(message: types.Message, state: FSMContext):
@dp.message_handler(is_admin=True, state=Post.price)
async def admin_form_price(message: types.message, state: FSMContext):
if len(message.text) > 30:
await bot.send_message(
message.chat.id,
("Цена не может быть больше 30 символов!\n"
"Повторите попытку")
)
await Post.price.set()
return
if not message.text.replace('.', '').replace(',', '').isdigit():
await Post.price.set()
await state.update_data(price=float(message.text.replace(",", ".")))

View File

@ -1,25 +1,25 @@
from aiogram import types
from aiogram.dispatcher import FSMContext
from load import dp, bot, messages
from state.state import AddUser
from utils.database.user import Register, User
from keyboard.default.admin.main_menu import base_menu
from keyboard.default.main_menu import back_to_main_menu
@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, state: FSMContext):
await bot.send_message(
message.chat.id,
("Отправьте user_id пользователя\n"
"Его можно узнать зайдя в информацию о пользователе"),
reply_markup=base_menu()
)
await AddUser.user_id.set()
await state.set_state("get_user_id_add_admin")
@dp.message_handler(state=AddUser.user_id)
async def add_admin1(message: types.Message, state):
@dp.message_handler(state="get_user_id_add_admin")
async def add_admin1(message: types.Message, state: FSMContext):
await state.finish()
user_id = message.text
if not user_id.isdigit() or "-100" in user_id:

View File

@ -0,0 +1,2 @@
from . import adding
from . import delete

View File

@ -0,0 +1,35 @@
from aiogram import types
from aiogram.dispatcher import FSMContext
from load import dp, bot, messages
from utils.database.user import Register, User
from keyboard.default.admin.main_menu import base_menu
from keyboard.default.main_menu import back_to_main_menu
@dp.message_handler(lambda x: x.text == messages.add_operator, is_admin=True)
async def add_operator(message: types.Message, state: FSMContext):
await bot.send_message(
message.chat.id,
("Отправьте user_id пользователя\n"
"Его можно узнать зайдя в информацию о пользователе"),
reply_markup=base_menu()
)
await state.set_state("get_user_id_add_operator")
@dp.message_handler(is_admin=True, state="get_user_id_add_operator")
async def add_operator1(message: types.Message, state: FSMContext):
await state.finish()
user_id = message.text
if not user_id.isdigit() or "-100" in user_id:
await bot.send_message(message.chat.id, "Данные не правильные!", reply_markup=back_to_main_menu)
return
user_id = int(user_id)
user = User.get_user(user_id)
if not user:
await bot.send_message(message.chat.id, "Пользователь не существует!", reply_markup=back_to_main_menu)
return
Register.register_operator(user)
await bot.send_message(message.chat.id, "Оператор добавлен!", reply_markup=back_to_main_menu)

View File

@ -0,0 +1,18 @@
from aiogram import types
from load import dp, bot, messages
from keyboard.inline.operator.user import item_list
from utils.database.base import get_full_operator
@dp.message_handler(lambda x: x.text == messages.del_operator, is_admin=True)
async def del_admin(message: types.Message):
users = get_full_operator()
user = users[0]
result = messages.admin_user.format(**user)
await bot.send_message(
message.chat.id,
result,
parse_mode="Markdown",
reply_markup=item_list(items=len(users) - 1)
)

0
handlers/admin/start.py Normal file
View File

View File

@ -1 +1,2 @@
from . import support
from . import user

View File

@ -0,0 +1,35 @@
from aiogram import types
from load import dp, messages
from keyboard.inline.admin.user import item_list
from utils.database.base import get_full_operator, del_operator
@dp.callback_query_handler(lambda c: c.data.split("|")[0] in ["operator_prev", "operator_next"], is_admin=True)
async def next_item_adm(callback: types.CallbackQuery):
data = callback.data.split("|")
count = int(data[1])
items = get_full_operator()
user = items[count]
await callback.message.edit_text(
messages.admin_user.format(**user),
reply_markup=item_list(count, len(items)-1, int(data[2])),
parse_mode="Markdown"
)
await callback.answer()
@dp.callback_query_handler(lambda x: x.data.split("|")[0] == "delete_operator")
async def delete_admin(callback: types.CallbackQuery):
data = callback.data.split("|")
count = int(data[1])
items = get_full_operator()
user = items[count]
if user["user_id"] == callback.from_user.id:
await dp.bot.send_message(callback.message.chat.id, "Вы не можете удалить сами себя")
await callback.answer()
return
del_operator(user["user_id"])
await dp.bot.send_message(callback.message.chat.id, f"Оператор {user['first_name']} удалён!")
await callback.answer()

View File

@ -12,13 +12,13 @@ async def cmd_menu(message: types.Message):
await bot.send_message(message.chat.id, "Operator panel", reply_markup=main_menu(active))
@dp.message_handler(lambda x: x.text == messages.leave_work)
@dp.message_handler(lambda x: x.text == messages.leave_work, is_operator=True)
async def leave_work(message: types.Message):
User.set_state(message.from_user.id)
await bot.send_message(message.chat.id, "Режим тех. поддержки отключён!", reply_markup=back_to_main_menu)
@dp.message_handler(lambda x: x.text == messages.on_work)
@dp.message_handler(lambda x: x.text == messages.on_work, is_operator=True)
async def on_work(message: types.Message):
User.set_state(message.from_user.id, True)
await bot.send_message(message.chat.id, "Режим тех. поддержки включён!", reply_markup=back_to_main_menu)

View File

@ -1,35 +1,95 @@
from aiogram import types
from aiogram.dispatcher import FSMContext
import config
from load import dp, bot, messages
from utils.database.cart import get_user_cart
from utils.database.market import Catalog
from utils.database.ordering import save_info
from keyboard.default.main_menu import back_to_main_menu
from keyboard.default.checkout import checkout_btn
from state.state import UserState
@dp.message_handler(lambda x: x.text == messages.checkout)
async def checkout(message: types.Message):
async def checkout(message: types.Message, state: FSMContext):
items = get_user_cart(message.from_user.id)
output: str = ""
output: list[str] = [""]
cost = 0
for index, count in items:
i = Catalog.get_catalog(index)
output += f'Имя: {i["name"]} цена: {i["price"]} - {count}шт.\n'
product_info = (
f'Имя: {i["name"]} '
f'цена: {i["price"]} - {count}шт.\n'
)
if (len(output[-1]) + len(product_info)) >= 4095:
output.append("")
output[-1] += product_info
cost += i["price"] * count
output += f"Общая сумма: {cost}\nВсё верно? Следующий этап: заполнение заявки"
await bot.send_message(message.chat.id, output, reply_markup=checkout_btn())
await UserState.confirm.set()
total_amount = (
f"Общая сумма: {cost}\n"
"Всё верно? Следующий этап: заполнение заявки"
)
if (len(output[-1]) + len(total_amount)) >= 4095:
output.append("")
output[-1] += total_amount
for msg in output:
await bot.send_message(message.chat.id, msg, reply_markup=checkout_btn())
await state.set_state("load_or_create_profile")
@dp.message_handler(lambda x: x.text == messages.all_right_message, state="save_or_continue")
async def continue_user_form():
pass
async def continue_user_form(message: types.Message, state: FSMContext):
chat_id = config.service_chat
items = get_user_cart(message.from_user.id)
data = await state.get_data()
output: list[str] = [
(f"Имя: {data['first_name']}\n"
f"Фамилия: {data['last_name']}\n"
f"Номер телефона: {data['phone_number']}\n"
f"Адрес: {data['address']}\n\n"
)
]
cost = 0
for index, count in items:
i = Catalog.get_catalog(index)
product_info = (
f'ID: {i["id"]} '
f'Имя: {i["name"]} '
f'цена: {i["price"]} - {count}шт.\n'
)
if (len(output[-1]) + len(product_info)) >= 4095:
output.append("")
output[-1] += product_info
cost += i["price"] * count
total_amount = (
f"\nИтоговая сумма: {cost}"
)
if (len(output[-1]) + len(total_amount)) >= 4095:
output.append("")
output[-1] += total_amount
await bot.send_message(message.chat.id, messages.order, reply_markup=back_to_main_menu)
for msg in output:
await bot.send_message(
chat_id,
msg,
parse_mode='Markdown'
)
await state.finish()
@dp.message_handler(lambda x: x.text == messages.save_and_continue, state="save_or_continue")
async def save_user_info(message: types.Message):
state = dp.current_state(chat=message.chat.id, user=message.from_user.id)
async def save_user_info(message: types.Message, state: FSMContext):
info = await state.get_data()
save_info(user_id=message.from_user.id, **info)
await continue_user_form()
await continue_user_form(message, state)

View File

@ -5,12 +5,11 @@ from load import dp, bot, messages
from keyboard.default.checkout import confirm_all_info
from keyboard.default.main_menu import cancel_btn, get_phone_number, continue_btn
from keyboard.default.ordering import load_info
from state.state import UserState
from state.checkout import Checkout
from utils.database.ordering import get_info
@dp.message_handler(lambda x: x.text == messages.all_right_message, state=UserState.confirm)
@dp.message_handler(lambda x: x.text == messages.all_right_message, state="load_or_create_profile")
async def confirm(message: types.Message, state: FSMContext):
await state.finish()
info = get_info(message.from_user.id)
@ -30,15 +29,15 @@ async def load_form(message: types.message, state: FSMContext):
first_name=info["first_name"],
last_name=info["last_name"],
phone_number=info["phone_number"],
address=info["address"]
address=info["address"],
load=True
)
await bot.send_message(message.chat.id, "Ваши данные загружены!", reply_markup=continue_btn)
await state.set_state("finish_send_form")
@dp.message_handler(lambda x: x.text == messages.rewrite_data, state="load_data")
async def new_form(message: types.Message, state: FSMContext = None):
await state.update_data(loaded=False)
async def new_form(message: types.Message):
await bot.send_message(
message.chat.id,
"Напишите вашу фамилию",
@ -100,11 +99,10 @@ async def finish_form(message: types.Message, state: FSMContext):
text = (f"Имя: {data['first_name']}\n"
f"Фамилия: {data['last_name']}\n"
f"Номер телефона: {data['phone_number']}\n"
f"Адрес: {data['address']}\n"
)
f"Адрес: {data['address']}\n")
await bot.send_message(
message.chat.id,
text,
reply_markup=confirm_all_info()
reply_markup=confirm_all_info(load=data.pop("load", False))
)
await state.set_state("save_or_continue")

View File

@ -1,10 +1,11 @@
from aiogram import types
from aiogram.dispatcher.filters import CommandStart
from aiogram.dispatcher.filters import CommandStart, CommandHelp
from load import dp, bot, messages
from keyboard.default.main_menu import main_menu
from utils.database.base import get_admins, get_operator
from utils.database.user import Register
from utils.database.market import Catalog
@dp.message_handler(CommandStart())
@ -30,6 +31,38 @@ async def back_to_menu(message: types.Message):
)
@dp.message_handler(commands='get')
async def get_item(message: types.Message):
args = message.get_args()
if not args and not args.isdigit():
await bot.send_message(message.chat.id, "Неверные данные")
return
item = Catalog.get_catalog(args)
if not item:
await bot.send_message(message.chat.id, "Товар не найден!")
return
await bot.send_photo(
chat_id=message.chat.id,
photo=item["image"],
caption=messages.product_message.format(
name=item["name"],
description=item["description"],
price=item['price']
),
parse_mode="Markdown",
)
@dp.message_handler(CommandHelp())
async def help_cmd(message: types.Message):
await bot.send_message(
message.chat.id,
("/sos - попросить помощь в оператора\n"
"/get <ID> - получить товар по ID")
)
@dp.message_handler(lambda x: x.text == messages.cancel_message, state="*")
async def cancel(message: types.Message):
state = dp.current_state(chat=message.chat.id, user=message.from_user.id)
@ -44,8 +77,3 @@ async def userinfo(message: types.Message):
"User_id: <code>{user_id}</code>".format(user_id=message.from_user.id),
parse_mode="HTML"
)
@dp.message_handler(commands=['test'])
async def test(message: types.Message):
Register.register_admin(message.from_user)

View File

@ -15,6 +15,7 @@ def main_menu():
admin_control.append(KeyboardButton(messages.del_admin))
if admin_control:
markup.add(*admin_control)
markup.add(KeyboardButton(messages.add_operator), KeyboardButton(messages.del_operator))
markup.add(KeyboardButton(messages.back))
return markup

View File

@ -10,9 +10,10 @@ def checkout_btn() -> ReplyKeyboardMarkup:
]], resize_keyboard=True)
def confirm_all_info():
def confirm_all_info(load: bool = False):
markup = ReplyKeyboardMarkup(resize_keyboard=True)
markup.add(KeyboardButton(messages.all_right_message))
markup.row(KeyboardButton(messages.save_and_continue))
if not load:
markup.row(KeyboardButton(messages.save_and_continue))
markup.row(KeyboardButton(messages.cancel_message))
return markup

View File

@ -9,4 +9,5 @@ def main_menu(active: bool = False) -> ReplyKeyboardMarkup:
markup.add(KeyboardButton(messages.leave_work))
else:
markup.add(KeyboardButton(messages.on_work))
markup.add(messages.back)
return markup

View File

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

View File

View File

View File

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

View File

@ -1,9 +0,0 @@
from aiogram.dispatcher.filters.state import StatesGroup, State
class UserState(StatesGroup):
confirm = State()
class AddUser(StatesGroup):
user_id = State()

View File

View File

@ -27,10 +27,26 @@ def get_full_admin():
return usr
def del_admin(user_id:int):
def get_full_operator():
usr = []
for i in Operator.select():
usr.append({
"user_id": i.user_id,
"first_name": i.first_name,
"last_name": i.last_name,
"username": i.username
})
return usr
def del_admin(user_id: int):
Admin.delete().where(Admin.user_id == user_id).execute()
def del_operator(user_id: int):
Operator.delete().where(Operator.user_id == user_id).execute()
def get_active_operator():
usr = []
for i in Operator.select().where(Operator.active==True):

View File

@ -1,7 +1,7 @@
from .model import Cart
def add_to_cart(user_id:int, item_id: int):
def add_to_cart(user_id: int, item_id: int):
if Cart.select().where(Cart.user_id==user_id, Cart.product_id==item_id).exists():
count = Cart.get(Cart.user_id==user_id, Cart.product_id==item_id).count
Cart.update(count=count+1).where(Cart.user_id==user_id, Cart.product_id==item_id).execute()
@ -10,14 +10,14 @@ def add_to_cart(user_id:int, item_id: int):
def del_from_cart(user_id: int, item_id: int):
Cart.delete().where(Cart.user_id==user_id, Cart.product_id==item_id).execute()
Cart.delete().where(Cart.user_id == user_id, Cart.product_id == item_id).execute()
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 = []
for i in Cart.select().where(Cart.user_id == user_id):
cart.append((i.product_id, i.count))

View File

@ -22,7 +22,7 @@ class Catalog:
return item
@classmethod
def get_catalog(cls, 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[t.List[t.Any], t.Dict[t.Any, t.Any]]:
if item_id:
if get_count:
return cls.__get_item(item_id), Model.select().count()

View File

@ -1,7 +1,7 @@
from .model import UserInfo
def save_info(user_id: int, last_name:str, first_name:str, phone_number:str, address:str, **kw):
def save_info(user_id: int, last_name: str, first_name: str, phone_number: str, address: str, **kw):
UserInfo.insert(
user_id=user_id,
first_name=first_name,

View File

@ -15,6 +15,7 @@ contact = "☎️ Предоставить номер телефона"
save_and_continue = "Сохранить данные и продолжить"
continue_ = "Продолжить"
order = "Заявка была отправлена!"
rewrite_data = "Ввести заново"
load_data = "Загрузить данные"
@ -30,6 +31,8 @@ add_post = "Добавить пост"
delete_post = "🗑️ Удалить пост"
add_admin = "Добавить админа"
del_admin = "Удалить админа"
add_operator = "Добавить оператора"
del_operator = "Удалить оператора"
admin_user = (
'Имя: [{first_name}](tg://user?id={user_id})\n'
'Фамилия: [{last_name}](tg://user?id={user_id})\n'