Сделано:
- Сделал работу комманд
This commit is contained in:
3
.gitignore
vendored
3
.gitignore
vendored
@@ -4,4 +4,5 @@ bin/
|
||||
include/
|
||||
lib/
|
||||
lib64/
|
||||
lib64
|
||||
lib64
|
||||
*.log
|
||||
BIN
__pycache__/db.cpython-312.pyc
Normal file
BIN
__pycache__/db.cpython-312.pyc
Normal file
Binary file not shown.
BIN
__pycache__/logger_config.cpython-312.pyc
Normal file
BIN
__pycache__/logger_config.cpython-312.pyc
Normal file
Binary file not shown.
102
bot.py
102
bot.py
@@ -1,12 +1,12 @@
|
||||
|
||||
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
|
||||
from telegram.ext import Application, CallbackQueryHandler, CommandHandler, ContextTypes
|
||||
from db import User
|
||||
from db import Subscription
|
||||
from db import Transaction
|
||||
from db import VPNServer
|
||||
from db import User, VPNServer, Transaction, Subscription
|
||||
from db import last_subscription, create_user , get_sub_list
|
||||
import db
|
||||
from sqlalchemy import desc
|
||||
import json
|
||||
import string
|
||||
from datetime import datetime
|
||||
from db import get_db_session
|
||||
from db import init_db, SessionLocal
|
||||
@@ -14,15 +14,9 @@ from logger_config import setup_logger
|
||||
with open('config.json', 'r') as file:
|
||||
config = json.load(file)
|
||||
|
||||
def last_subscription(session,user):
|
||||
last_subscription = (
|
||||
session.query(Subscription)
|
||||
.filter(Subscription.user_id == user.id)
|
||||
.order_by(desc(Subscription.created_at))
|
||||
.first()
|
||||
)
|
||||
return last_subscription
|
||||
|
||||
|
||||
logger = setup_logger()
|
||||
|
||||
|
||||
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
keyboard = [
|
||||
@@ -47,16 +41,20 @@ async def personal_account(update: Update, context: ContextTypes.DEFAULT_TYPE) -
|
||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
|
||||
session = next(get_db_session())
|
||||
user = session.query(User).filter(User.telegram_id == update.chat_member.from_user.id).first()
|
||||
check = last_subscription(session=session,user=user)
|
||||
|
||||
if not check:
|
||||
if session.query(User).filter(User.telegram_id == str(update.effective_user.id)).first() == None:
|
||||
create_user(str(update.effective_user.id),update.effective_user.username)
|
||||
user = session.query(User).filter(User.telegram_id == str(update.effective_user.id)).first()
|
||||
|
||||
subscription = last_subscription(session=session,user=user)
|
||||
|
||||
if not subscription:
|
||||
await update.message.reply_text(f'Профиль {user.username}\nВы не приобретали ещё у нас подписку, но это явно стоит сделать:)',reply_markup=reply_markup)
|
||||
# проверяем, истекла ли подписка
|
||||
if check.expiry_date < datetime.now():
|
||||
await update.message.reply_text(f'Ваш профиль {user.username},Ваша подписка действует до - {check.expiry_date}',reply_markup=reply_markup)
|
||||
elif subscription.expiry_date < datetime.now():
|
||||
await update.message.reply_text(f'Ваш профиль {user.username},Ваша подписка действует до - {subscription.expiry_date}',reply_markup=reply_markup)
|
||||
else:
|
||||
await update.message.reply_text(f'Ваш профиль {user.username},\nВаша подписка истекла - {check.expiry_date}',reply_markup=reply_markup)
|
||||
await update.message.reply_text(f'Ваш профиль {user.username},\nВаша подписка истекла - {subscription.expiry_date}',reply_markup=reply_markup)
|
||||
|
||||
async def about(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
keyboard = [
|
||||
@@ -83,11 +81,68 @@ async def pop_up(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
await update.message.reply_text(f'Когда нибудь эта штука заработает',reply_markup=reply_markup)
|
||||
|
||||
#async def buy_subscription(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
async def buy_subscription(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
keyboard = [
|
||||
[
|
||||
InlineKeyboardButton("Главное меню", callback_data="account"),
|
||||
]]
|
||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
session = next(get_db_session())
|
||||
user = session.query(User).filter(User.telegram_id == str(update.effective_user.id)).first()
|
||||
check = last_subscription(session=session,user=user)
|
||||
|
||||
if not check:
|
||||
keyboard = [
|
||||
[
|
||||
InlineKeyboardButton("Тариф 1 \"Бимжик\"", callback_data="bimzhik"),
|
||||
],
|
||||
[
|
||||
InlineKeyboardButton("Тариф 2 \"Бизнес хомячёк\"", callback_data="homyachok"),
|
||||
],
|
||||
[
|
||||
InlineKeyboardButton("Тариф 2 \"Продвинутый Акулёнок\"", callback_data="akulenok"),
|
||||
]]
|
||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
await update.message.reply_text(f'Какую подписку вы хотели бы приобрести\nТариф 1 "Бимжик" - 200 рубликов - 1 месяцок\nТариф 2 "Бизнес хомячёк" - 500 рубликов - 3 месяцка\nТариф 3 "Продвинутый Акулёнок" - 888 рубликов - 888 рубликов\n',reply_markup=reply_markup)
|
||||
# проверяем, истекла ли подписка
|
||||
else:
|
||||
keyboard = [
|
||||
[
|
||||
InlineKeyboardButton("Главное меню", callback_data="account"),
|
||||
]]
|
||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
await update.message.reply_text(f'У вас уже приобретена подписка',reply_markup=reply_markup)
|
||||
|
||||
|
||||
async def faq(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
keyboard = [
|
||||
[
|
||||
InlineKeyboardButton("Главное меню", callback_data="account"),
|
||||
]]
|
||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
await update.message.reply_text(f'Когда нибудь что нибудь здесь будет написано!!;)',reply_markup=reply_markup)
|
||||
async def active_sub(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
keyboard = [
|
||||
[
|
||||
InlineKeyboardButton("Главное меню", callback_data="account"),
|
||||
]]
|
||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
session = next(get_db_session())
|
||||
list_sub = get_sub_list(session, 10, update.effective_user.id)
|
||||
|
||||
if list_sub:
|
||||
message = "Ваши подписки:\n"
|
||||
for cur_sub in list_sub:
|
||||
if cur_sub.expiry_date > datetime.now():
|
||||
message += f" Активная: {cur_sub.plan}, Дата покупки: {cur_sub.created_at}\n"
|
||||
else:
|
||||
message += f" Устаревшая: {cur_sub.plan}, Дата покупки: {cur_sub.created_at}\n"
|
||||
else:
|
||||
message = "Ты пидор, не приобрел у нас подписку?!"
|
||||
await update.message.reply_text(message,reply_markup=reply_markup)
|
||||
|
||||
def main() -> None:
|
||||
logger = setup_logger()
|
||||
|
||||
init_db()
|
||||
db = SessionLocal()
|
||||
application = Application.builder().token(config['token']).build()
|
||||
@@ -97,7 +152,10 @@ def main() -> None:
|
||||
application.add_handler(CommandHandler("about", about))
|
||||
application.add_handler(CommandHandler("support", support))
|
||||
application.add_handler(CommandHandler("popup", pop_up))
|
||||
#application.add_handler(CommandHandler("buy_subscription", buy_subscription))
|
||||
application.add_handler(CommandHandler("buy_subscription", buy_subscription))
|
||||
application.add_handler(CommandHandler("faq", faq))
|
||||
application.add_handler(CommandHandler("active_sub", active_sub))
|
||||
|
||||
|
||||
application.run_polling(allowed_updates=Update.ALL_TYPES)
|
||||
db.close()
|
||||
|
||||
43
db.py
43
db.py
@@ -1,14 +1,55 @@
|
||||
from sqlalchemy import create_engine, Column, String, Integer, Numeric, DateTime, ForeignKey, Text
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker, relationship
|
||||
from sqlalchemy import desc
|
||||
from datetime import datetime
|
||||
import json
|
||||
import uuid
|
||||
with open('config.json', 'r') as file : config = json.load(file)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
def generate_uuid():
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def last_subscription(session,user):
|
||||
last_subscription = (
|
||||
session.query(Subscription)
|
||||
.filter(Subscription.user_id == user.id)
|
||||
.order_by(desc(Subscription.created_at))
|
||||
.first()
|
||||
)
|
||||
return last_subscription
|
||||
def get_sub_list(session,count,user_id):
|
||||
subscriptions = (
|
||||
session.query(Subscription)
|
||||
.filter(Subscription.user_id == str(user_id))
|
||||
.order_by(desc(Subscription.created_at))
|
||||
.limit(count) # Ограничиваем результат 10 записями
|
||||
.all() # Получаем все записи
|
||||
)
|
||||
return subscriptions
|
||||
|
||||
def create_user(telegram_id: str, username: str = None, balance: float = 0.0):
|
||||
db = next(get_db_session())
|
||||
try:
|
||||
new_user = User(
|
||||
telegram_id=telegram_id,
|
||||
username=username,
|
||||
balance=balance
|
||||
)
|
||||
db.add(new_user)
|
||||
db.commit()
|
||||
db.refresh(new_user)
|
||||
return new_user
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise e
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
#Пользователи
|
||||
class User(Base):
|
||||
__tablename__ = 'users'
|
||||
@@ -67,7 +108,7 @@ class VPNServer(Base):
|
||||
subscriptions = relationship("Subscription", back_populates="vpn_server")
|
||||
|
||||
# Настройка подключения к базе данных
|
||||
DATABASE_URL = "postgresql://vpn_bot_user:yourpassword@localhost/vpn_bot_db"
|
||||
DATABASE_URL = f"postgresql://{config['username']}:{config['password_DB']}@localhost/bot_db"
|
||||
|
||||
engine = create_engine(DATABASE_URL)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
@@ -12,7 +12,7 @@ with open('config.json', 'r') as file : config = json.load(file)
|
||||
class UserService:
|
||||
def __init__(self,logger):
|
||||
self.logger = logger
|
||||
|
||||
|
||||
def add_user(self,telegram_id: int, username: str):
|
||||
session = next(get_db_session())
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user