Структура проекта

your_project/
│
├── .env
├── requirements.txt
├── main.py
├── users.db            # Новая база данных SQLite (создается после инициализации)
├── app/
│   ├── __init__.py
│   ├── settings.py
│   ├── views.py
│   ├── db.py            # Новый файл для базы данных
│   ├── handlers/
│   │   ├── __init__.py
│   │   ├── business_handler.py
│   │   ├── events.py
│   ├── middlewares/
│   │   ├── __init__.py
│   │   ├── business_middleware.py
│   ├── utils/
│   │   ├── __init__.py
│   │   ├── openai_actions.py
│   │   ├── check_delay.py
Файл .env

token=12345:abcd
admin_id=123456789
openai_key=sk-abcd
openai_base_url=https://lk.neuroapi.host/v1
delay=10
Файл requirements.txt

aiogram==3.6.0
pydantic-settings==2.2.1
openai==1.29.0
pytz==2024.1
httpx==0.27.0
SQLAlchemy==2.0.16
aiosqlite==0.19.0
Файл main.py

import asyncio

from aiogram import Dispatcher
from aiogram.methods import DeleteWebhook

from app.handlers.business_handler import handle_business_message
from app.handlers.events import start_bot, stop_bot
from app.middlewares.business_middleware import BusinessMiddleware
from app.settings import bot, init_db

async def start():
    await init_db()  # Инициализация базы данных

    dp = Dispatcher()

    dp.update.middleware(BusinessMiddleware())

    dp.startup.register(start_bot)
    dp.shutdown.register(stop_bot)

    dp.business_message.register(handle_business_message)

    try:
        await bot(DeleteWebhook(drop_pending_updates=True))
        await dp.start_polling(bot)
    finally:
        await bot.session.close()

if __name__ == "__main__":
    asyncio.run(start())
Файл app/settings.py

from aiogram import Bot
from pydantic_settings import BaseSettings
from app.db import engine, Base

class Secrets(BaseSettings):
    token: str
    admin_id: int
    openai_key: str
    openai_base_url: str
    delay: int

    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"

secrets = Secrets()

# Инициализация базы данных
async def init_db():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

bot = Bot(token=secrets.token, parse_mode="Markdown")
Файл app/db.py

from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker, declarative_base

DATABASE_URL = "sqlite+aiosqlite:///./users.db"

# Создание асинхронного движка базы данных
engine: AsyncEngine = create_async_engine(DATABASE_URL, echo=True)

# Создание асинхронной сессии
SessionLocal = sessionmaker(
    bind=engine, class_=AsyncSession, expire_on_commit=False
)

# Базовый класс для моделей
Base = declarative_base()

from sqlalchemy import Column, Integer, Float

class UserDelay(Base):
    __tablename__ = "user_delays"

    user_id = Column(Integer, primary_key=True, index=True, unique=True, nullable=False)
    last_message_time = Column(Float, nullable=False)
Файл app/views.py

def start_bot_message():
    return "Бот запущен"

def stop_bot_message():
    return "Бот остановлен"

def system_prompt():
    return """Ты бот помощник и ты должен помогать людям."""
Файл app/middlewares/business_middleware.py

from typing import Callable, Dict, Any, Awaitable

import httpx
from aiogram import BaseMiddleware
from aiogram.dispatcher.middlewares.user_context import EventContext
from aiogram.types import TelegramObject, ChatFullInfo

from app.settings import secrets

class BusinessMiddleware(BaseMiddleware):
    async def __call__(
        self,
        handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]],
        event: TelegramObject,
        data: Dict[str, Any],
    ) -> Any:
        async with httpx.AsyncClient() as client:
            response = await client.get(
                f"https://api.telegram.org/bot{secrets.token}/getChat?chat_id={secrets.admin_id}"
            )
            if response.status_code != 200:
                # Обработка ошибки при получении информации о чате
                return

            chat = response.json()
            full_chat = ChatFullInfo(**chat["result"])

            context: EventContext = data.get("event_context")

            if (
                context.user.id != secrets.admin_id
                and hasattr(context, 'business_connection_id') and context.business_connection_id
            ):
                return await handler(event, data)
Файл app/utils/openai_actions.py

import httpx
from aiogram.types import Message
from openai import AsyncOpenAI

from app.settings import secrets
from app.views import system_prompt

async def get_chat_completion(message: Message):
    http_client = httpx.AsyncClient(
        limits=httpx.Limits(max_connections=100, max_keepalive_connections=20)
    )
    client = AsyncOpenAI(
        api_key=secrets.openai_key,
        http_client=http_client,
        base_url=secrets.openai_base_url,
    )

    messages = [
        {"role": "system", "content": system_prompt()},
        {"role": "user", "content": message.text},
    ]

    response = await client.chat.completions.create(
        model="gpt-3.5-turbo", messages=messages, max_tokens=1000, temperature=0.8
    )

    return response.choices[0].message.content
Файл app/utils/check_delay.py

import asyncio
from sqlalchemy.future import select

from app.db import SessionLocal, UserDelay
from app.settings import secrets

async def check_user_delay(user_id: int) -> bool:
    async with SessionLocal() as session:
        result = await session.execute(
            select(UserDelay).where(UserDelay.user_id == user_id)
        )
        user = result.scalar_one_or_none()

        current_time = asyncio.get_event_loop().time()

        if user:
            time_since_last_message = current_time - user.last_message_time
            if time_since_last_message < secrets.delay * 60:
                return False  # Задержка ещё действует
            else:
                user.last_message_time = current_time
                session.add(user)
                await session.commit()
                return True  # Задержка прошла, обновлено время
        else:
            new_user = UserDelay(user_id=user_id, last_message_time=current_time)
            session.add(new_user)
            await session.commit()
            return True  # Новый пользователь, разрешено сообщение
Файл app/handlers/business_handler.py

from aiogram.types import Message

from app.utils.check_delay import check_user_delay
from app.utils.openai_actions import get_chat_completion

async def handle_business_message(message: Message):
    if await check_user_delay(message.from_user.id) and message.text:
        answer = await get_chat_completion(message)
        await message.reply(answer)
Файл app/handlers/events.py

from app.settings import bot, secrets
from app import views

async def start_bot():
    await bot.send_message(secrets.admin_id, views.start_bot_message())

async def stop_bot():
    await bot.send_message(secrets.admin_id, views.stop_bot_message())
Файлы __init__.py
Все файлы __init__.py могут быт


# app/__init__.py

# app/handlers/__init__.py

# app/middlewares/__init__.py

# app/utils/__init__.py         { убери то что ипользуется ща за модель и добавь выбор моделей [from openai import OpenAI
from os import getenv

# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key=getenv("OPENROUTER_API_KEY"),
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer": $YOUR_SITE_URL, # Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_APP_NAME, # Optional. Shows in rankings on openrouter.ai.
  },
  model="liquid/lfm-40b:free",
  messages=[
    {
      "role": "user",
      "content": "What is the meaning of life?"
    }
  ]
)
print(completion.choices[0].message.content)][from openai import OpenAI
from os import getenv

# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key=getenv("OPENROUTER_API_KEY"),
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer": $YOUR_SITE_URL, # Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_APP_NAME, # Optional. Shows in rankings on openrouter.ai.
  },
  model="google/gemini-flash-1.5-8b-exp",
  messages=[
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "What's in this image?"
        },
        {
          "type": "image_url",
          "image_url": {
            "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
          }
        }
      ]
    }
  ]
)
print(completion.choices[0].message.content)][from openai import OpenAI
from os import getenv

# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key=getenv("OPENROUTER_API_KEY"),
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer": $YOUR_SITE_URL, # Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_APP_NAME, # Optional. Shows in rankings on openrouter.ai.
  },
  model="google/gemini-flash-1.5-exp",
  messages=[
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "What's in this image?"
        },
        {
          "type": "image_url",
          "image_url": {
            "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
          }
        }
      ]
    }
  ]
)
print(completion.choices[0].message.content)][from openai import OpenAI
from os import getenv

# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key=getenv("OPENROUTER_API_KEY"),
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer": $YOUR_SITE_URL, # Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_APP_NAME, # Optional. Shows in rankings on openrouter.ai.
  },
  model="nousresearch/hermes-3-llama-3.1-405b:free",
  messages=[
    {
      "role": "user",
      "content": "What is the meaning of life?"
    }
  ]
)
print(completion.choices[0].message.content)][from openai import OpenAI
from os import getenv

# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key=getenv("OPENROUTER_API_KEY"),
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer": $YOUR_SITE_URL, # Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_APP_NAME, # Optional. Shows in rankings on openrouter.ai.
  },
  model="google/gemini-pro-1.5-exp",
  messages=[
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "What's in this image?"
        },
        {
          "type": "image_url",
          "image_url": {
            "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
          }
        }
      ]
    }
  ]
)
print(completion.choices[0].message.content)][from openai import OpenAI
from os import getenv

# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key=getenv("OPENROUTER_API_KEY"),
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer": $YOUR_SITE_URL, # Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_APP_NAME, # Optional. Shows in rankings on openrouter.ai.
  },
  model="meta-llama/llama-3.1-70b-instruct:free",
  messages=[
    {
      "role": "user",
      "content": "What is the meaning of life?"
    }
  ]
)
print(completion.choices[0].message.content)][meta-llama/llama-3.1-405b-instruct:free][from openai import OpenAI
from os import getenv

# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key=getenv("OPENROUTER_API_KEY"),
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer": $YOUR_SITE_URL, # Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_APP_NAME, # Optional. Shows in rankings on openrouter.ai.
  },
  model="meta-llama/llama-3.2-11b-vision-instruct:free",
  messages=[
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "What's in this image?"
        },
        {
          "type": "image_url",
          "image_url": {
            "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
          }
        }
      ]
    }
  ]
)
print(completion.choices[0].message.content)][from openai import OpenAI
from os import getenv

# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key=getenv("OPENROUTER_API_KEY"),
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer": $YOUR_SITE_URL, # Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_APP_NAME, # Optional. Shows in rankings on openrouter.ai.
  },
  model="qwen/qwen-2-7b-instruct:free",
  messages=[
    {
      "role": "user",
      "content": "What is the meaning of life?"
    }
  ]
)
print(completion.choices[0].message.content)][from openai import OpenAI
from os import getenv

# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key=getenv("OPENROUTER_API_KEY"),
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer": $YOUR_SITE_URL, # Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_APP_NAME, # Optional. Shows in rankings on openrouter.ai.
  },
  model="google/gemma-2-9b-it:free",
  messages=[
    {
      "role": "user",
      "content": "What is the meaning of life?"
    }
  ]
)
print(completion.choices[0].message.content)][from openai import OpenAI
from os import getenv

# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key=getenv("OPENROUTER_API_KEY"),
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer": $YOUR_SITE_URL, # Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_APP_NAME, # Optional. Shows in rankings on openrouter.ai.
  },
  model="microsoft/phi-3-medium-128k-instruct:free",
  messages=[
    {
      "role": "user",
      "content": "What is the meaning of life?"
    }
  ]
)
print(completion.choices[0].message.content)][from openai import OpenAI
from os import getenv

# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key=getenv("OPENROUTER_API_KEY"),
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer": $YOUR_SITE_URL, # Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_APP_NAME, # Optional. Shows in rankings on openrouter.ai.
  },
  model="gryphe/mythomist-7b:free",
  messages=[
    {
      "role": "user",
      "content": "What is the meaning of life?"
    }
  ]
)
print(completion.choices[0].message.content)][from openai import OpenAI
from os import getenv

# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key=getenv("OPENROUTER_API_KEY"),
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer": $YOUR_SITE_URL, # Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_APP_NAME, # Optional. Shows in rankings on openrouter.ai.
  },
  model="mistralai/mistral-7b-instruct:free",
  messages=[
    {
      "role": "user",
      "content": "What is the meaning of life?"
    }
  ]
)
print(completion.choices[0].message.content)]}