Updated structure and json work

This commit is contained in:
2025-09-15 17:44:24 +03:00
parent d13d6e7916
commit 9b26946e06
12 changed files with 91 additions and 56 deletions

View File

@ -0,0 +1,15 @@
Project template for simple telegram bots
Features:
- Base commands with FSM (no redis)
- JSON data storage
- Async worker function
- Cute project structure
.env example:
```.env
botToken="token:from-botfather"
whitelist=["userid"]
dataPath="data/"
jsonFilename="data.json"
```

9
src/app/createApp.py Normal file
View File

@ -0,0 +1,9 @@
import asyncio
from app.jsonData import start as start_json
from app.telegram import start_bot
def createApp():
start_json()
asyncio.run(start_bot())

View File

@ -1,5 +1,5 @@
from connect import load, start
from utils import add, check, removeById, removeByParam
from .connect import load, start
from .utils import add, check, removeById, removeByParam
__all__ = [
"load",

View File

@ -0,0 +1,47 @@
import json
import os
import shutil
import sys
from datetime import datetime
from loguru import logger
from app.settings import settings
dataPath = settings.dataPath.removesuffix("/")
jsonRawFilename = settings.jsonFilename.removesuffix(".json")
backupPath = dataPath + "/backup"
filePath = dataPath + "/" + jsonRawFilename + ".json"
def start():
# Inits JSON file
try:
if not(os.path.exists(dataPath)):
os.mkdir(dataPath)
if not(os.path.exists(backupPath)):
os.mkdir(backupPath)
if os.path.exists(filePath):
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
backupFilePath = backupPath + "/" + jsonRawFilename + f"_backup_{timestamp}.json"
shutil.copy(filePath, backupFilePath)
logger.info(f"JSON backup was created: {backupFilePath}")
with open(filePath, "w") as f:
json.dump({}, f, ensure_ascii = False, indent=4)
logger.success(f"Successfully initialized JSON with path: {filePath}")
except Exception as e:
logger.error(f"Failed to initialize JSON: {e}")
sys.exit(1)
def load():
# Returnes the contents of the JSON file as a dictionary
data = {}
try:
with open(filePath, "r") as f:
data = json.load(f)
except json.decoder.JSONDecodeError:
logger.warning("JSON file is empty!")
return data

View File

@ -1,9 +1,9 @@
import json
from connect import load
from loguru import logger
from ..settings import settings
from app.jsonData.connect import load
from app.settings import settings
def getParamId(param):
@ -34,7 +34,7 @@ def removeById(id: int):
if id in currentData:
del currentData[id]
with open(settings.jsonPath, 'w', encoding = 'utf-8') as f:
with open(settings.jsonFilename, 'w', encoding = 'utf-8') as f:
json.dump(currentData, f, ensure_ascii = False, indent = 4)
logger.info(f'Id {id} was deleted successfully!')
return 0
@ -62,7 +62,7 @@ def add(param):
id = currentData[-1][0] + 1
newData = {id: param}
with open(settings.jsonPath, 'w', encoding = 'utf-8') as f:
with open(settings.jsonFilename, 'w', encoding = 'utf-8') as f:
currentData.update(newData)
json.dump(currentData, f, ensure_ascii = False, indent = 4)
logger.info(f"Param {param} was added with id {id}")

View File

@ -5,9 +5,10 @@ class Settings(BaseSettings):
botToken: str
whitelist: list
jsonPath: str
dataPath: str
jsonFilename: str
modelConfig = SettingsConfigDict(env_file = ".env", env_file_encoding="utf-8")
model_config = SettingsConfigDict(env_file = ".env", env_file_encoding="utf-8")
settings = Settings() # type: ignore

View File

@ -0,0 +1,3 @@
from .telegram import start_bot
__all__ = ["start_bot"]

View File

@ -1,6 +1,5 @@
import asyncio
import strings
from aiogram import Bot, Dispatcher, F, Router
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
@ -11,9 +10,10 @@ from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.types import BotCommand, BotCommandScopeDefault, Message
from loguru import logger
import jsonData
from internal.internal import internal
from settings import settings
from app import jsonData
from app.internal.internal import internal
from app.settings import settings
from app.telegram import strings
async def setCommands():
@ -112,6 +112,7 @@ async def startBot():
await bot.send_message(chat_id=i, text=strings.startBot)
except Exception as e:
logger.error(e)
logger.success("Started bot")
async def stopBot():
try:
@ -119,10 +120,10 @@ async def stopBot():
await bot.send_message(chat_id=i, text=strings.stopBot)
except Exception as e:
logger.error(e)
logger.success("Stopped bot")
async def start_bot() -> None:
logger.info("Started bot!")
dp.startup.register(startBot)
dp.include_router(strategyRouter)
dp.include_router(removeRouter)

View File

@ -1,39 +0,0 @@
import json
import os
import shutil
from datetime import datetime
from loguru import logger
from ..settings import settings
def start():
# Inits JSON file
filePath = settings.jsonPath
if not(os.path.exists('data')):
os.mkdir('data')
if not(os.path.exists('data/backup')):
os.mkdir('data/backup')
if os.path.exists(filePath):
timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
backupPath = (f'data/backup/data_backup_{timestamp}.json')
shutil.copy(filePath, backupPath)
logger.info(f'JSON backup was created: {backupPath}')
with open(filePath, 'w') as f:
json.dump({}, f, ensure_ascii = False, indent=4)
logger.info(f'New {filePath} created with empty JSON.')
def load():
# Returnes the contents of the JSON file as a dictionary
data = {}
try:
with open(settings.jsonPath, 'r') as f:
data = json.load(f)
except json.decoder.JSONDecodeError:
logger.warning('JSON file is empty!')
return data

View File

@ -1,5 +1,3 @@
import asyncio
from app.createApp import createApp
from telegram.telegram import start_bot
asyncio.run(start_bot())
createApp()