Skip to content

Commit

Permalink
Merge pull request #61 from ZhuchkaTriplesix/develop
Browse files Browse the repository at this point in the history
refactor
  • Loading branch information
ZhuchkaTriplesix authored May 14, 2024
2 parents 44a2321 + f6e4e37 commit 8dc95a4
Show file tree
Hide file tree
Showing 16 changed files with 112 additions and 70 deletions.
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
TOKEN=telegram.token
POSTGRES_SERVER=db.example.com
POSTGRES_USER=user
POSTGRES_PASSWORD=pass
POSTGRES_DB=app
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Byte-compiled / optimized / DLL files
users_time.json
user_list.json
.env
__pycache__/
*.py[cod]
*$py.class
Expand All @@ -17,8 +18,6 @@ cases.json
.idea/vcs.xml
users.db
.DS_Store
docker-compose.yaml
Dockerfile
data/config.py
# Distribution / packaging
.Python
Expand Down
28 changes: 28 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
FROM python:3.11

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Set working directory in the container
WORKDIR /price_bot

# Install system dependencies
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
gcc \
gettext \
&& rm -rf /var/lib/apt/lists/*

# Install Python dependencies
COPY requirements.txt /code/
RUN pip install --no-cache-dir -r requirements.txt

# Copy the application code into the container
COPY . /code/

# Expose the port the application runs on
EXPOSE 8080

# Run the application
CMD ["python", "main.py"]
31 changes: 31 additions & 0 deletions core/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from typing import Any, Dict, Optional
from dotenv import find_dotenv, load_dotenv
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import PostgresDsn, validator

load_dotenv(find_dotenv(".env"))


class Settings(BaseSettings):
model_config = SettingsConfigDict(case_sensitive=True)
TOKEN: str
POSTGRES_SERVER: str
POSTGRES_USER: str
POSTGRES_PASSWORD: str
POSTGRES_DB: str
SQLALCHEMY_DATABASE_URI: PostgresDsn | None = None

@validator("SQLALCHEMY_DATABASE_URI", pre=True)
def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any:
if isinstance(v, str):
return v
return PostgresDsn.build(
scheme="postgresql+pg8000",
username=values.get("POSTGRES_USER"),
password=values.get("POSTGRES_PASSWORD"),
host=values.get("POSTGRES_SERVER"),
path=values.get("POSTGRES_DB"),
)


settings = Settings()
3 changes: 0 additions & 3 deletions data/__init__.py

This file was deleted.

16 changes: 14 additions & 2 deletions models.py → db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base, scoped_session
import datetime
from data.config import host, user, password, db_name
from core.config import settings
import pg8000

Base = declarative_base()

engine = create_engine(f'postgresql+pg8000://{user}:{password}@{host}/{db_name}', echo=False)
engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, echo=False)

Session = sessionmaker(bind=engine)
session = scoped_session(Session)
Expand All @@ -25,6 +25,7 @@ class Users(Base):
created_date = Column(DateTime, default=datetime.datetime.utcnow)
updated_at = Column(DateTime, default=datetime.datetime.utcnow)

@staticmethod
def add_user(telegram_id: int, username: str):
session = Session()
user = session.query(Users).where(Users.telegram_id == telegram_id).first()
Expand All @@ -34,11 +35,13 @@ def add_user(telegram_id: int, username: str):
user = Users(telegram_id=telegram_id, username=username)
Users.add_close(user, session)

@staticmethod
def add_close(user, session):
session.add(user)
session.commit()
session.close()

@staticmethod
def add_admin(telegram_id: int, username: str):
session = Session()
user = session.query(Users).where(Users.telegram_id == telegram_id).first()
Expand All @@ -48,6 +51,7 @@ def add_admin(telegram_id: int, username: str):
user = Users(username=username, telegram_id=telegram_id, group_id=2)
Users.add_close(user, session)

@staticmethod
def change_access(telegram_id: int, group_id: int) -> object:
session = Session()
user = session.query(Users).where(Users.telegram_id == telegram_id).first()
Expand All @@ -60,6 +64,7 @@ def change_access(telegram_id: int, group_id: int) -> object:
else:
return False

@staticmethod
def check_vip(telegram_id: int) -> object:
user = session.query(Users).where(Users.telegram_id == telegram_id).first()
user_group = user.group_id
Expand All @@ -68,6 +73,7 @@ def check_vip(telegram_id: int) -> object:
else:
return False

@staticmethod
def check_owner(telegram_id: int) -> object:
user = session.query(Users).where(Users.telegram_id == telegram_id).first()
user_group = user.group_id
Expand All @@ -76,6 +82,7 @@ def check_owner(telegram_id: int) -> object:
else:
return False

@staticmethod
def check_admin(telegram_id: int) -> object:
user = session.query(Users).where(Users.telegram_id == telegram_id).first()
user_group = user.group_id
Expand All @@ -84,6 +91,7 @@ def check_admin(telegram_id: int) -> object:
else:
return False

@staticmethod
def get_id(telegram_id: int) -> object:
user = session.query(Users).where(Users.telegram_id == telegram_id).first()
user_id = user.id
Expand All @@ -98,6 +106,7 @@ class Items(Base):
hash_name = Column(String(length=60))
item_count = Column(Integer)

@staticmethod
def add_item(telegram_id: int, hash_name: str, item_count: int):
session = Session()
user_id = Users.get_id(telegram_id)
Expand All @@ -112,6 +121,7 @@ def add_item(telegram_id: int, hash_name: str, item_count: int):
session.commit()
session.close()

@staticmethod
def user_items(telegram_id: int) -> object:
session = Session()
user_id = Users.get_id(telegram_id)
Expand All @@ -124,6 +134,7 @@ def user_items(telegram_id: int) -> object:
user_item.update(u)
return user_item

@staticmethod
def delete_item(telegram_id: int, hash_name: str):
session = Session()
user_id = Users.get_id(telegram_id)
Expand All @@ -142,6 +153,7 @@ class LogBase(Base):
function_name = Column(String(length=12))
time_used = Column(DateTime, default=datetime.datetime.utcnow)

@staticmethod
def add(telegram_id: int, username: str, function_name: str):
session = Session()
func = LogBase(telegram_id=telegram_id, username=username, function_name=function_name)
Expand Down
16 changes: 16 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
version: '3.8'

services:
postgres:
image: postgres:latest
restart: always

bot:
build: .
restart: always
depends_on:
- postgres
volumes:
- .:/price_bot
ports:
- "8080:8080"
4 changes: 2 additions & 2 deletions handlers/admin.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from aiogram import F
from aiogram.fsm.state import StatesGroup, State
from aiogram.types import Message
import keyboards as kb
from misc import keyboards as kb
from aiogram import Router
from aiogram.fsm.context import FSMContext
import sys
import models
from db import models

router = Router()

Expand Down
6 changes: 3 additions & 3 deletions handlers/client.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from aiogram import F
from aiogram.types import Message, CallbackQuery
import steammarket as sm
from data import json_support, case_translation
import keyboards as kb
from misc import json_support, case_translation
from misc import keyboards as kb
from aiogram import Router
import models
from db import models

router = Router()
json_data = "user_list.json"
Expand Down
4 changes: 2 additions & 2 deletions handlers/vip.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
from aiogram.types import Message, CallbackQuery
from aiogram import Router
from aiogram.fsm.context import FSMContext
import models
import keyboards as kb
from db import models
from misc import keyboards as kb
import steammarket as sm
from data.config import sell_fee

Expand Down
7 changes: 3 additions & 4 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import asyncio
from aiogram import Bot, Dispatcher
from handlers import client, admin, vip
from core.config import settings


async def main():
with open("token.txt", "r") as TOKEN:
bot_token = TOKEN.readline()
bot = Bot(bot_token)
bot = Bot(settings.TOKEN)
dp = Dispatcher()
dp.include_routers(admin.router, vip.router, client.router) # routers add
await dp.start_polling(bot, skip_updates=True)
Expand All @@ -16,4 +15,4 @@ async def main():
try:
asyncio.run(main())
except KeyboardInterrupt:
print("main error")
print("Start error")
File renamed without changes.
File renamed without changes.
File renamed without changes.
7 changes: 7 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
aiogram~=3.6.0
pg8000~=1.31.2
SQLAlchemy~=2.0.30
python-dotenv~=1.0.1
pydantic-settings
pydantic~=2.7.1
steammarket~=0.2.7
52 changes: 0 additions & 52 deletions user_list.json

This file was deleted.

0 comments on commit 8dc95a4

Please sign in to comment.