diff --git a/README.md b/README.md index f2900fe..3e6a0c4 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ Detailed architecture documentation for each project: - **[api-gateway](https://github.com/deep-assistant/api-gateway/blob/main/ARCHITECTURE.md)** - OpenAI-compatible API gateway with multi-provider failover - **[telegram-bot](https://github.com/deep-assistant/telegram-bot/blob/main/ARCHITECTURE.md)** - Dual-language Telegram bot (Python/JavaScript) +- **[vk-bot](https://github.com/deep-assistant/master-plan/blob/issue-1-3afa1eac/VK-BOT-ARCHITECTURE.md)** - VK (VKontakte) bot with dual Python/JavaScript implementation *(in development)* - **[GPTutor](https://github.com/deep-assistant/GPTutor/blob/main/ARCHITECTURE.md)** - Multi-platform educational AI (VK/Telegram mini apps) - **[web-capture](https://github.com/deep-assistant/web-capture/blob/main/ARCHITECTURE.md)** - Web page capture microservice (HTML/Markdown/PNG) diff --git a/VK-BOT-ARCHITECTURE.md b/VK-BOT-ARCHITECTURE.md new file mode 100644 index 0000000..6c7b498 --- /dev/null +++ b/VK-BOT-ARCHITECTURE.md @@ -0,0 +1,1150 @@ +# VK Bot Architecture + +**Version:** 1.0.0 +**License:** Unlicense +**Runtime:** Python 3.10+ / Node.js 18+ +**Primary Frameworks:** vkbottle (Python), node-vk-bot-api (JavaScript) +**Status:** Draft Proposal + +## Overview + +The VK Bot is a dual-language chatbot implementation for VKontakte (VK.com) platform, designed to provide users access to multiple LLM models through VK communities. This bot serves as a complementary interface to the existing VK mini app in the GPTutor project, offering conversational AI capabilities directly through VK messages. + +Like the Telegram bot, this implementation supports both Python and JavaScript runtimes while maintaining architectural consistency with the deep-assistant ecosystem. + +### Key Features + +- **Multi-model LLM Chat**: Access to GPT-4, Claude, Gemini, and other models via API Gateway +- **Image Generation**: DALL-E integration for text-to-image generation +- **Image Editing**: Background removal, upscaling, and style transfer +- **Payment Processing**: VK Donut/VK Pay integration for token purchases +- **Referral System**: User acquisition and reward mechanism +- **Music Generation**: Suno AI integration (optional) +- **Token-based Balance**: Unified billing system with API Gateway +- **Multi-language Support**: Russian and English interfaces + +### Design Principles + +1. **Architectural Consistency**: Mirror telegram-bot structure for maintainability +2. **API Gateway Integration**: Leverage existing backend infrastructure +3. **Dual Runtime Support**: Python and JavaScript implementations with feature parity +4. **Community-First Design**: Optimized for VK community interactions +5. **Graceful Degradation**: Handle API failures and rate limits elegantly + +## System Architecture + +### High-Level Architecture + +``` +┌─────────────────────────────────────────────────────────────┐ +│ VK Platform │ +│ (Community Messages, VK Bots Long Poll API) │ +└───────────────────────┬─────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ VK Bot Service │ +│ ┌──────────────────────────────────────────────────────┐ │ +│ │ Python Bot (vkbottle) │ JavaScript Bot (node-vk) │ │ +│ ├─────────────────────────┴────────────────────────────┤ │ +│ │ Router Layer (Message Handlers) │ │ +│ │ - GPT Chat Router │ │ +│ │ - Image Generation Router │ │ +│ │ - Payment Router │ │ +│ │ - Referral Router │ │ +│ │ - Settings Router │ │ +│ ├───────────────────────────────────────────────────────┤ │ +│ │ Services Layer │ │ +│ │ - API Gateway Service (LLM, Images, TTS) │ │ +│ │ - Database Service (User State, Balance, History) │ │ +│ │ - Payment Service (VK Pay/Donut) │ │ +│ │ - Analytics Service │ │ +│ ├───────────────────────────────────────────────────────┤ │ +│ │ Database Layer │ │ +│ │ - SQLite/Vedis (Python) or Redis (JavaScript) │ │ +│ │ - Tokens, Dialogs, Users, Referrals │ │ +│ └───────────────────────────────────────────────────────┘ │ +└───────────────────────┬─────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ API Gateway Service │ +│ (OpenAI-compatible proxy with multi-provider failover) │ +└─────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ LLM Provider Ecosystem │ +│ OpenAI │ Anthropic │ DeepSeek │ Gemini │ Meta Llama │ +└─────────────────────────────────────────────────────────────┘ +``` + +### Component Interaction Flow + +``` +User → VK Community → Long Poll API → VK Bot → Router → Service → API Gateway → LLM Provider + ↓ + Database + (State/Balance) +``` + +## Directory Structure + +### Python Bot Structure + +``` +vk-bot/ +├── bot/ +│ ├── __init__.py +│ ├── bot_run.py # Main entry point for Python bot +│ ├── config.py # Configuration management +│ ├── routers/ +│ │ ├── __init__.py +│ │ ├── gpt.py # GPT chat router +│ │ ├── image.py # Image generation router +│ │ ├── payment.py # Payment processing router +│ │ ├── referral.py # Referral system router +│ │ └── settings.py # Bot settings router +│ ├── middlewares/ +│ │ ├── __init__.py +│ │ ├── auth.py # User authentication +│ │ ├── balance.py # Token balance checks +│ │ └── logging.py # Request logging +│ ├── keyboards/ +│ │ ├── __init__.py +│ │ ├── main_menu.py # Main keyboard layouts +│ │ ├── models.py # Model selection keyboards +│ │ └── payment.py # Payment keyboards +│ └── utils/ +│ ├── __init__.py +│ ├── text.py # Text formatting helpers +│ └── validators.py # Input validation +├── services/ +│ ├── __init__.py +│ ├── api_gateway.py # API Gateway client +│ ├── database.py # Database operations +│ ├── payment.py # VK payment integration +│ └── analytics.py # Usage analytics +├── db/ +│ ├── __init__.py +│ ├── models.py # Database models +│ ├── migrations/ # Database migrations +│ └── repositories/ # Data access layer +│ ├── __init__.py +│ ├── users.py +│ ├── tokens.py +│ ├── dialogs.py +│ └── referrals.py +├── tests/ +│ ├── __init__.py +│ ├── test_routers.py +│ ├── test_services.py +│ └── test_database.py +├── requirements.txt +├── requirements-dev.txt +├── Dockerfile +├── docker-compose.yml +├── .env.example +└── README.md +``` + +### JavaScript Bot Structure + +``` +vk-bot/ +├── js/ +│ ├── src/ +│ │ ├── index.js # Main entry point for JS bot +│ │ ├── config.js # Configuration management +│ │ ├── routers/ +│ │ │ ├── gpt.js # GPT chat router +│ │ │ ├── image.js # Image generation router +│ │ │ ├── payment.js # Payment processing router +│ │ │ ├── referral.js # Referral system router +│ │ │ └── settings.js # Bot settings router +│ │ ├── middlewares/ +│ │ │ ├── auth.js # User authentication +│ │ │ ├── balance.js # Token balance checks +│ │ │ └── logging.js # Request logging +│ │ ├── keyboards/ +│ │ │ ├── mainMenu.js # Main keyboard layouts +│ │ │ ├── models.js # Model selection keyboards +│ │ │ └── payment.js # Payment keyboards +│ │ ├── services/ +│ │ │ ├── apiGateway.js # API Gateway client +│ │ │ ├── database.js # Database operations +│ │ │ ├── payment.js # VK payment integration +│ │ │ └── analytics.js # Usage analytics +│ │ └── utils/ +│ │ ├── text.js # Text formatting helpers +│ │ └── validators.js # Input validation +│ ├── tests/ +│ │ ├── routers.test.js +│ │ ├── services.test.js +│ │ └── database.test.js +│ ├── package.json +│ ├── package-lock.json +│ └── .env.example +├── Dockerfile.js +└── docker-compose.js.yml +``` + +## Core Components + +### 1. Bot Framework Layer + +#### Python Implementation (vkbottle) + +```python +from vkbottle.bot import Bot +from vkbottle import Keyboard, KeyboardButtonColor, Text + +bot = Bot(token="YOUR_VK_GROUP_TOKEN") + +@bot.on.message(text="/start") +async def start_handler(message): + keyboard = ( + Keyboard() + .add(Text("💬 Chat with GPT"), color=KeyboardButtonColor.PRIMARY) + .row() + .add(Text("🎨 Generate Image"), color=KeyboardButtonColor.POSITIVE) + ) + return await message.answer( + "Welcome! Choose an action:", + keyboard=keyboard.get_json() + ) + +bot.run_forever() +``` + +#### JavaScript Implementation (node-vk-bot-api) + +```javascript +const VkBot = require('node-vk-bot-api'); +const { Keyboard } = require('node-vk-bot-api'); + +const bot = new VkBot(process.env.VK_GROUP_TOKEN); + +bot.command('/start', async (ctx) => { + const keyboard = Keyboard.builder() + .textButton({ label: '💬 Chat with GPT', color: Keyboard.PRIMARY_COLOR }) + .row() + .textButton({ label: '🎨 Generate Image', color: Keyboard.POSITIVE_COLOR }) + .build(); + + await ctx.reply('Welcome! Choose an action:', null, keyboard); +}); + +bot.startPolling(); +``` + +### 2. Router Layer + +Routers handle specific feature domains and delegate business logic to services. + +#### GPT Chat Router (Python) + +```python +from vkbottle.bot import Message +from vkbottle import BaseStateGroup + +class ConversationState(BaseStateGroup): + WAITING_FOR_MESSAGE = "waiting_for_message" + WAITING_FOR_MODEL_SELECTION = "waiting_for_model_selection" + +@bot.on.message(state=ConversationState.WAITING_FOR_MESSAGE) +async def handle_gpt_message(message: Message): + # Check user balance + balance = await database_service.get_user_balance(message.from_id) + if balance <= 0: + return await message.answer("Insufficient balance. Please top up.") + + # Send to API Gateway + response = await api_gateway_service.chat_completion( + user_id=message.from_id, + message=message.text, + model="gpt-4" + ) + + # Update balance + await database_service.deduct_tokens( + user_id=message.from_id, + tokens=response.tokens_used + ) + + return await message.answer(response.content) +``` + +#### Image Generation Router (JavaScript) + +```javascript +bot.on((ctx) => { + if (ctx.message.text && ctx.message.text.startsWith('/imagine')) { + return handleImageGeneration(ctx); + } +}); + +async function handleImageGeneration(ctx) { + const prompt = ctx.message.text.replace('/imagine', '').trim(); + + if (!prompt) { + return ctx.reply('Please provide a prompt: /imagine '); + } + + // Check user balance + const balance = await databaseService.getUserBalance(ctx.message.from_id); + if (balance < 100) { + return ctx.reply('Insufficient balance. Image generation costs 100 tokens.'); + } + + // Generate image via API Gateway + const result = await apiGatewayService.generateImage({ + userId: ctx.message.from_id, + prompt: prompt, + model: 'dall-e-3' + }); + + // Upload to VK and send + const upload = await bot.uploadDocument({ + peer_id: ctx.message.peer_id, + file: result.imageUrl + }); + + return ctx.reply('Here is your image:', null, null, [upload]); +} +``` + +### 3. Services Layer + +Services encapsulate business logic and external API interactions. + +#### API Gateway Service + +```python +import aiohttp +from typing import Optional, Dict, Any + +class APIGatewayService: + def __init__(self, base_url: str, token: str): + self.base_url = base_url + self.token = token + self.session: Optional[aiohttp.ClientSession] = None + + async def chat_completion( + self, + user_id: int, + message: str, + model: str = "gpt-4", + stream: bool = False + ) -> Dict[str, Any]: + """Send chat completion request to API Gateway.""" + async with self.session.post( + f"{self.base_url}/v1/chat/completions", + headers={"Authorization": f"Bearer {self.token}"}, + json={ + "model": model, + "messages": [{"role": "user", "content": message}], + "user_id": str(user_id), + "stream": stream + } + ) as response: + response.raise_for_status() + return await response.json() + + async def generate_image( + self, + user_id: int, + prompt: str, + model: str = "dall-e-3" + ) -> Dict[str, Any]: + """Generate image via API Gateway.""" + async with self.session.post( + f"{self.base_url}/v1/images/generations", + headers={"Authorization": f"Bearer {self.token}"}, + json={ + "model": model, + "prompt": prompt, + "user_id": str(user_id) + } + ) as response: + response.raise_for_status() + return await response.json() + + async def get_user_balance(self, user_id: int) -> int: + """Get user token balance from API Gateway.""" + async with self.session.get( + f"{self.base_url}/tokens/{user_id}", + headers={"Authorization": f"Bearer {self.token}"} + ) as response: + response.raise_for_status() + data = await response.json() + return data.get("balance", 0) +``` + +#### Database Service + +```python +from sqlalchemy import create_engine, Column, Integer, String, DateTime +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker +from datetime import datetime + +Base = declarative_base() + +class User(Base): + __tablename__ = 'users' + + vk_id = Column(Integer, primary_key=True) + username = Column(String) + first_name = Column(String) + last_name = Column(String) + referrer_id = Column(Integer, nullable=True) + created_at = Column(DateTime, default=datetime.utcnow) + +class DatabaseService: + def __init__(self, db_path: str): + self.engine = create_engine(f'sqlite:///{db_path}') + Base.metadata.create_all(self.engine) + self.Session = sessionmaker(bind=self.engine) + + def get_or_create_user(self, vk_id: int, **kwargs) -> User: + """Get existing user or create new one.""" + session = self.Session() + user = session.query(User).filter_by(vk_id=vk_id).first() + + if not user: + user = User(vk_id=vk_id, **kwargs) + session.add(user) + session.commit() + + session.close() + return user +``` + +### 4. Payment Integration + +#### VK Donut Integration (Python) + +```python +from vkbottle import VKAPIError + +class PaymentService: + def __init__(self, bot, api_gateway_service): + self.bot = bot + self.api_gateway = api_gateway_service + + async def create_payment_link( + self, + user_id: int, + amount: int, + tokens: int + ) -> str: + """Create VK Donut payment link.""" + # VK Pay integration for direct payments + link = await self.bot.api.request( + "donut.getSubscription", + { + "owner_id": -self.bot.group_id, + "user_id": user_id + } + ) + return link + + async def handle_payment_notification(self, notification: dict): + """Handle payment webhook from VK.""" + user_id = notification.get("user_id") + amount = notification.get("amount") + + # Calculate tokens (e.g., 100 RUB = 1000 tokens) + tokens = amount * 10 + + # Add tokens via API Gateway + await self.api_gateway.add_tokens(user_id, tokens) +``` + +## Message Flow + +### User Message Processing Flow + +``` +1. VK User sends message → VK Community +2. VK Long Poll API delivers event → VK Bot +3. Middleware chain: + a. Authentication Middleware (get/create user) + b. Logging Middleware (record request) + c. Balance Middleware (check tokens) +4. Router matches message to handler +5. Handler delegates to Service +6. Service calls API Gateway +7. API Gateway processes request (LLM/Image) +8. Service updates database (deduct tokens) +9. Handler formats response +10. Bot sends reply → VK API → User +``` + +### Streaming Response Flow (Python) + +```python +@bot.on.message(text="/stream ") +async def stream_handler(message: Message, prompt: str): + # Send initial message + msg = await message.answer("Generating response...") + + full_response = "" + async for chunk in api_gateway_service.chat_completion_stream( + user_id=message.from_id, + message=prompt + ): + full_response += chunk + + # Update message every 10 chunks + if len(full_response) % 100 == 0: + await bot.api.messages.edit( + peer_id=message.peer_id, + message=full_response, + conversation_message_id=msg.conversation_message_id + ) + + # Final update + await bot.api.messages.edit( + peer_id=message.peer_id, + message=full_response, + conversation_message_id=msg.conversation_message_id + ) +``` + +## Configuration + +### Environment Variables + +#### Python Bot (.env) + +```bash +# VK Configuration +VK_GROUP_TOKEN=vk1.a.your_group_token_here +VK_GROUP_ID=123456789 + +# API Gateway +API_GATEWAY_URL=https://api.deep-assistant.com +API_GATEWAY_TOKEN=your_api_gateway_master_token + +# Database +DATABASE_PATH=./data/vk_bot.db + +# Payment +VK_PAY_MERCHANT_ID=your_merchant_id +VK_PAY_SECRET=your_payment_secret + +# Analytics (optional) +ANALYTICS_TOKEN=your_analytics_token + +# Logging +LOG_LEVEL=INFO +LOG_FILE=./logs/vk_bot.log + +# Features +ENABLE_SUNO=true +ENABLE_IMAGE_GENERATION=true +ENABLE_REFERRAL_SYSTEM=true + +# Rate Limiting +MAX_REQUESTS_PER_MINUTE=30 +MAX_REQUESTS_PER_HOUR=500 +``` + +#### JavaScript Bot (.env) + +```bash +# VK Configuration +VK_GROUP_TOKEN=vk1.a.your_group_token_here +VK_GROUP_ID=123456789 + +# API Gateway +API_GATEWAY_URL=https://api.deep-assistant.com +API_GATEWAY_TOKEN=your_api_gateway_master_token + +# Redis (for JS bot state) +REDIS_URL=redis://localhost:6379 +REDIS_PASSWORD=your_redis_password + +# Payment +VK_PAY_MERCHANT_ID=your_merchant_id +VK_PAY_SECRET=your_payment_secret + +# Features +ENABLE_SUNO=true +ENABLE_IMAGE_GENERATION=true +ENABLE_REFERRAL_SYSTEM=true +``` + +## Deployment + +### Docker Deployment (Python) + +```dockerfile +# Dockerfile +FROM python:3.10-slim + +WORKDIR /app + +# Install dependencies +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy application +COPY bot/ ./bot/ +COPY services/ ./services/ +COPY db/ ./db/ + +# Create data directories +RUN mkdir -p /app/data /app/logs + +# Run bot +CMD ["python", "-m", "bot.bot_run"] +``` + +```yaml +# docker-compose.yml +version: '3.8' + +services: + vk-bot-python: + build: . + container_name: vk-bot-python + restart: unless-stopped + env_file: + - .env + volumes: + - ./data:/app/data + - ./logs:/app/logs + networks: + - deep-assistant-network + + vk-bot-js: + build: + context: . + dockerfile: Dockerfile.js + container_name: vk-bot-js + restart: unless-stopped + env_file: + - js/.env + depends_on: + - redis + networks: + - deep-assistant-network + + redis: + image: redis:7-alpine + container_name: vk-bot-redis + restart: unless-stopped + command: redis-server --requirepass ${REDIS_PASSWORD} + volumes: + - redis-data:/data + networks: + - deep-assistant-network + +networks: + deep-assistant-network: + external: true + +volumes: + redis-data: +``` + +### Production Deployment + +1. **Obtain VK Access Tokens**: + - Create VK Community + - Enable Community Messages (Manage → Messages) + - Generate Access Token (Settings → API usage → Tokens) + - Enable Long Poll API (Settings → API usage → Long Poll API) + +2. **Configure API Gateway**: + - Set up API Gateway service (see api-gateway repository) + - Generate master token for bot authentication + - Configure failover providers + +3. **Deploy Bot**: + ```bash + # Clone repository + git clone https://github.com/deep-assistant/vk-bot.git + cd vk-bot + + # Configure environment + cp .env.example .env + nano .env # Edit with your tokens + + # Run with Docker Compose + docker-compose up -d + + # Check logs + docker-compose logs -f vk-bot-python + ``` + +4. **Verify Deployment**: + - Send `/start` message to your VK community + - Check bot responds with main menu + - Test GPT chat functionality + - Verify token balance integration + +## Commands + +### User Commands + +- `/start` - Initialize bot and show main menu +- `/help` - Display help information and available commands +- `/balance` - Check current token balance +- `/models` - List available LLM models +- `/settings` - Configure bot preferences (language, default model) +- `/referral` - Get referral link and view statistics +- `/history` - View recent conversation history +- `/clear` - Clear conversation context + +### Admin Commands + +- `/stats` - View bot usage statistics (admin only) +- `/broadcast ` - Send message to all users (admin only) +- `/user ` - View user information (admin only) + +### Image Commands + +- `/imagine ` - Generate image with DALL-E +- `/edit ` - Edit uploaded image +- `/upscale` - Upscale uploaded image +- `/rembg` - Remove background from image + +### Payment Commands + +- `/buy` - Purchase tokens +- `/prices` - View token packages and prices +- `/transactions` - View payment history + +## Internationalization + +### Language Support + +The bot supports multiple languages with automatic detection based on user preferences or manual selection. + +#### Language Files Structure + +``` +locales/ +├── en.json # English +├── ru.json # Russian +└── ... +``` + +#### Example Locale File (en.json) + +```json +{ + "welcome": "Welcome to Deep Assistant VK Bot!", + "main_menu": { + "chat": "💬 Chat with GPT", + "image": "🎨 Generate Image", + "balance": "💰 Balance", + "settings": "⚙️ Settings" + }, + "errors": { + "insufficient_balance": "Insufficient balance. Please top up to continue.", + "api_error": "Sorry, an error occurred. Please try again.", + "invalid_prompt": "Please provide a valid prompt." + }, + "balance": { + "current": "Your current balance: {tokens} tokens", + "low_balance": "Low balance warning: {tokens} tokens remaining" + } +} +``` + +## Error Handling + +### Error Types and Responses + +```python +from enum import Enum + +class ErrorType(Enum): + INSUFFICIENT_BALANCE = "insufficient_balance" + API_ERROR = "api_error" + RATE_LIMIT = "rate_limit" + INVALID_INPUT = "invalid_input" + UNAUTHORIZED = "unauthorized" + +async def handle_error(error: Exception, message: Message): + """Central error handler.""" + if isinstance(error, InsufficientBalanceError): + return await message.answer( + "⚠️ Insufficient balance.\n" + "Please purchase tokens to continue: /buy" + ) + elif isinstance(error, RateLimitError): + return await message.answer( + "⏱️ Rate limit exceeded.\n" + "Please wait a moment before trying again." + ) + elif isinstance(error, APIError): + logger.error(f"API Error: {error}") + return await message.answer( + "❌ An error occurred while processing your request.\n" + "Please try again or contact support if the issue persists." + ) + else: + logger.exception(f"Unexpected error: {error}") + return await message.answer( + "❌ An unexpected error occurred.\n" + "Our team has been notified." + ) +``` + +## Dependencies + +### Python Dependencies (requirements.txt) + +``` +vkbottle>=4.3.0 +aiohttp>=3.8.0 +sqlalchemy>=2.0.0 +python-dotenv>=1.0.0 +pydantic>=2.0.0 +redis>=4.5.0 +pillow>=10.0.0 +``` + +### JavaScript Dependencies (package.json) + +```json +{ + "dependencies": { + "node-vk-bot-api": "^4.0.0", + "axios": "^1.6.0", + "redis": "^4.6.0", + "dotenv": "^16.0.0", + "pino": "^8.0.0", + "sharp": "^0.33.0" + }, + "devDependencies": { + "jest": "^29.0.0", + "eslint": "^8.0.0", + "nodemon": "^3.0.0" + } +} +``` + +## Testing + +### Unit Tests (Python) + +```python +import pytest +from bot.routers.gpt import handle_gpt_message +from services.api_gateway import APIGatewayService + +@pytest.mark.asyncio +async def test_gpt_message_handler(): + """Test GPT message handling.""" + # Mock message and services + mock_message = MockMessage( + from_id=123456, + text="Hello, GPT!" + ) + + # Test handler + response = await handle_gpt_message(mock_message) + + assert response is not None + assert isinstance(response, str) + +@pytest.mark.asyncio +async def test_insufficient_balance(): + """Test behavior with insufficient balance.""" + mock_message = MockMessage( + from_id=999999, # User with zero balance + text="Hello" + ) + + with pytest.raises(InsufficientBalanceError): + await handle_gpt_message(mock_message) +``` + +### Integration Tests (JavaScript) + +```javascript +const { VkBot } = require('./src/index'); +const { apiGatewayService } = require('./src/services/apiGateway'); + +describe('VK Bot Integration', () => { + test('should handle /start command', async () => { + const ctx = mockContext({ text: '/start' }); + await bot.handleMessage(ctx); + + expect(ctx.reply).toHaveBeenCalledWith( + expect.stringContaining('Welcome') + ); + }); + + test('should generate image with valid prompt', async () => { + const ctx = mockContext({ text: '/imagine a sunset' }); + const result = await handleImageGeneration(ctx); + + expect(result).toBeDefined(); + expect(apiGatewayService.generateImage).toHaveBeenCalled(); + }); +}); +``` + +## Logging + +### Logging Configuration (Python) + +```python +import logging +from logging.handlers import RotatingFileHandler + +def setup_logging(log_level: str = "INFO", log_file: str = "vk_bot.log"): + """Configure logging with rotation.""" + logger = logging.getLogger("vk_bot") + logger.setLevel(getattr(logging, log_level)) + + # Console handler + console_handler = logging.StreamHandler() + console_handler.setFormatter( + logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + ) + + # File handler with rotation + file_handler = RotatingFileHandler( + log_file, + maxBytes=10*1024*1024, # 10MB + backupCount=5 + ) + file_handler.setFormatter( + logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + ) + + logger.addHandler(console_handler) + logger.addHandler(file_handler) + + return logger +``` + +## Performance Characteristics + +### Expected Performance + +- **Message Processing Latency**: 100-500ms (excluding LLM response time) +- **Concurrent Users**: 1000+ per instance +- **Database Operations**: <50ms per query (SQLite) +- **Memory Footprint**: ~200MB (Python), ~150MB (JavaScript) +- **API Gateway Latency**: 1-5 seconds (LLM dependent) + +### Optimization Strategies + +1. **Connection Pooling**: Reuse HTTP connections to API Gateway +2. **Caching**: Cache user preferences and model lists +3. **Async Operations**: Non-blocking I/O for all external calls +4. **Batch Processing**: Group database operations +5. **Rate Limiting**: Prevent API abuse and reduce costs + +## Security Considerations + +### Authentication & Authorization + +1. **Token Security**: Store VK tokens securely in environment variables +2. **User Verification**: Validate VK user IDs on each request +3. **Admin Commands**: Restrict admin commands to verified administrator IDs +4. **Payment Verification**: Validate VK payment webhooks with signatures + +### Data Protection + +1. **User Privacy**: Store minimal user data (VK ID, balance, preferences) +2. **Conversation History**: Optional, user-controlled retention +3. **Payment Information**: Never store payment card details +4. **API Keys**: Rotate regularly, use separate keys for dev/prod + +### Rate Limiting + +```python +from collections import defaultdict +from datetime import datetime, timedelta + +class RateLimiter: + def __init__(self, max_per_minute: int = 30, max_per_hour: int = 500): + self.max_per_minute = max_per_minute + self.max_per_hour = max_per_hour + self.user_requests = defaultdict(list) + + def is_allowed(self, user_id: int) -> bool: + """Check if user has exceeded rate limits.""" + now = datetime.utcnow() + requests = self.user_requests[user_id] + + # Remove old requests + requests = [req for req in requests if req > now - timedelta(hours=1)] + + # Check limits + recent_minute = len([r for r in requests if r > now - timedelta(minutes=1)]) + recent_hour = len(requests) + + if recent_minute >= self.max_per_minute or recent_hour >= self.max_per_hour: + return False + + # Add current request + requests.append(now) + self.user_requests[user_id] = requests + return True +``` + +## Known Issues & TODOs + +### Current Limitations + +1. **VK API Restrictions**: + - Community cannot initiate conversations (user must message first) + - File upload size limits (up to 200MB) + - No native streaming support (messages must be edited) + +2. **Feature Gaps**: + - Suno AI integration pending API availability + - Video generation not yet implemented + - Multi-language support limited to EN/RU + +### Future Enhancements + +- [ ] Add voice message transcription via Whisper +- [ ] Implement text-to-speech responses +- [ ] Add group chat support with context awareness +- [ ] Integrate web search for real-time information +- [ ] Add document processing (PDF, DOCX) +- [ ] Implement conversation export functionality +- [ ] Add analytics dashboard for users +- [ ] Support VK Mini App integration for rich UI + +## Troubleshooting + +### Common Issues + +#### Bot Not Responding + +**Symptoms**: Bot doesn't reply to messages + +**Solutions**: +1. Verify Community Messages are enabled (Manage → Messages) +2. Check Long Poll API is active (Settings → API usage → Long Poll API) +3. Verify access token has `messages` scope +4. Check bot logs for errors: `docker-compose logs -f vk-bot-python` + +#### Payment Not Working + +**Symptoms**: Payment links not generated or webhook not received + +**Solutions**: +1. Verify VK Pay merchant credentials +2. Check webhook URL is configured correctly +3. Ensure webhook signature validation is working +4. Test payment in VK test environment first + +#### Database Errors + +**Symptoms**: SQLite locked errors or connection issues + +**Solutions**: +1. Check file permissions on database file +2. Verify only one bot instance is running +3. Consider switching to PostgreSQL for production +4. Enable WAL mode: `PRAGMA journal_mode=WAL;` + +#### API Gateway Timeouts + +**Symptoms**: Requests to API Gateway fail or timeout + +**Solutions**: +1. Verify API Gateway is running and accessible +2. Check network connectivity and firewall rules +3. Increase timeout values in configuration +4. Review API Gateway logs for errors + +## API Integration + +### VK API Methods Used + +- `messages.send` - Send messages to users +- `messages.edit` - Edit existing messages (for streaming) +- `docs.getMessagesUploadServer` - Get upload URL for documents +- `docs.save` - Save uploaded document +- `photos.getMessagesUploadServer` - Get upload URL for photos +- `photos.saveMessagesPhoto` - Save uploaded photo +- `groups.getLongPollServer` - Get Long Poll server URL +- `donut.getSubscription` - Payment integration + +### API Gateway Endpoints Used + +- `POST /v1/chat/completions` - LLM chat completions +- `POST /v1/images/generations` - Image generation +- `POST /v1/audio/transcriptions` - Audio transcription +- `POST /v1/audio/speech` - Text-to-speech +- `GET /tokens/{user_id}` - Get user balance +- `POST /tokens/{user_id}/add` - Add tokens to user +- `GET /dialogs/{user_id}` - Get conversation history + +## Development + +### Setup Development Environment + +```bash +# Clone repository +git clone https://github.com/deep-assistant/vk-bot.git +cd vk-bot + +# Python setup +python -m venv venv +source venv/bin/activate # On Windows: venv\Scripts\activate +pip install -r requirements.txt +pip install -r requirements-dev.txt + +# JavaScript setup +cd js +npm install + +# Configure environment +cp .env.example .env +# Edit .env with your development tokens + +# Run tests +pytest # Python +npm test # JavaScript + +# Run in development mode +python -m bot.bot_run # Python +npm run dev # JavaScript +``` + +### Contributing Guidelines + +1. Fork the repository +2. Create a feature branch: `git checkout -b feature/your-feature-name` +3. Write tests for new functionality +4. Ensure all tests pass: `pytest` / `npm test` +5. Follow code style: `black .` / `npm run lint` +6. Commit with clear messages: `git commit -m "Add feature X"` +7. Push and create pull request + +## License + +This project is released into the public domain under the Unlicense. See LICENSE file for details. + +## Contributors + +- Deep Assistant Team + +## Glossary + +- **VK (VKontakte)**: Russian social networking service +- **Long Poll API**: VK API method for receiving real-time updates +- **Community**: VK group/page that can host bots +- **API Gateway**: Unified proxy service for multiple LLM providers +- **vkbottle**: Asynchronous Python framework for VK bots +- **node-vk-bot-api**: Node.js framework for VK bots +- **Token**: Internal currency unit for API usage billing +- **VK Donut**: VK's subscription/donation service +- **VK Pay**: VK's payment processing system diff --git a/VK-BOT-IMPLEMENTATION-PLAN.md b/VK-BOT-IMPLEMENTATION-PLAN.md new file mode 100644 index 0000000..7df9549 --- /dev/null +++ b/VK-BOT-IMPLEMENTATION-PLAN.md @@ -0,0 +1,636 @@ +# VK Bot Implementation Plan + +**Issue:** [#1 - VK bot (based on https://vk.com/gptutor) additional to the VK mini app](https://github.com/deep-assistant/master-plan/issues/1) +**Status:** Planning Phase +**Target Repository:** `deep-assistant/vk-bot` (new repository) +**Related PR:** [#29](https://github.com/deep-assistant/master-plan/pull/29) + +## Executive Summary + +This document outlines the step-by-step implementation plan for creating a VK (VKontakte) bot that complements the existing VK mini app in the GPTutor project. The bot will follow the architecture patterns established in the `telegram-bot` repository, with dual Python and JavaScript implementations. + +## Goals + +1. **Create VK Bot Repository**: Set up a new repository with proper structure and documentation +2. **Python Implementation**: Build a functional VK bot using `vkbottle` framework +3. **JavaScript Implementation**: Build an equivalent VK bot using `node-vk-bot-api` framework +4. **API Gateway Integration**: Connect both implementations to the existing API Gateway +5. **Feature Parity**: Implement core features matching the Telegram bot (GPT chat, images, payments) +6. **Production Readiness**: Add Docker deployment, testing, and monitoring + +## Architecture Overview + +The VK bot will serve as a conversational interface to the Deep Assistant ecosystem, allowing VK users to interact with multiple LLM models through VK community messages. It will integrate with the existing API Gateway for backend services. + +``` +VK User → VK Community → VK Bot → API Gateway → LLM Providers + ↓ + Database + (User State/Balance) +``` + +See [VK-BOT-ARCHITECTURE.md](./VK-BOT-ARCHITECTURE.md) for comprehensive architecture details. + +## Prerequisites + +### VK Platform Setup + +- [ ] Create VK Community for the bot +- [ ] Enable Community Messages (Manage → Messages) +- [ ] Configure Bot Settings (Manage → Messages → Bot Settings) +- [ ] Enable Long Poll API (Settings → API usage → Long Poll API) +- [ ] Generate Access Token with `messages` scope +- [ ] Configure VK Pay merchant account (for payments) + +### Infrastructure Setup + +- [ ] Ensure API Gateway is running and accessible +- [ ] Obtain API Gateway master token for bot authentication +- [ ] Set up Redis instance (for JavaScript bot state) +- [ ] Configure domain/hosting for production deployment +- [ ] Set up monitoring and logging infrastructure + +## Implementation Phases + +### Phase 1: Repository Setup (Week 1) + +**Objective:** Create new repository with proper structure and documentation + +#### Tasks + +1. **Create Repository** + - [ ] Request creation of `deep-assistant/vk-bot` repository + - [ ] Initialize with Unlicense (matching organization standard) + - [ ] Set up branch protection rules for `main` + +2. **Project Structure** + ``` + vk-bot/ + ├── bot/ # Python implementation + ├── js/ # JavaScript implementation + ├── docs/ # Additional documentation + ├── examples/ # Example scripts and experiments + ├── .github/ + │ └── workflows/ # CI/CD workflows + ├── ARCHITECTURE.md # Architecture documentation + ├── README.md # Main documentation + ├── CONTRIBUTING.md # Contribution guidelines + ├── LICENSE # Unlicense + └── .gitignore + ``` + +3. **Documentation** + - [ ] Copy `VK-BOT-ARCHITECTURE.md` to new repository + - [ ] Create comprehensive `README.md` with: + - Project description + - Quick start guide + - Installation instructions + - Configuration guide + - Usage examples + - Development setup + - [ ] Create `CONTRIBUTING.md` with: + - Code style guidelines + - Testing requirements + - Pull request process + - Development workflow + +4. **Configuration Files** + - [ ] Create `.env.example` for Python bot + - [ ] Create `js/.env.example` for JavaScript bot + - [ ] Create `.gitignore` (Python + JavaScript + common patterns) + - [ ] Create `.dockerignore` + +**Deliverables:** +- New repository with complete structure +- Comprehensive documentation +- Configuration templates + +--- + +### Phase 2: Python Bot Core (Week 2-3) + +**Objective:** Implement minimal working Python bot with GPT chat functionality + +#### Tasks + +1. **Setup Python Environment** + - [ ] Create `requirements.txt` with dependencies: + - `vkbottle>=4.3.0` + - `aiohttp>=3.8.0` + - `sqlalchemy>=2.0.0` + - `python-dotenv>=1.0.0` + - `pydantic>=2.0.0` + - [ ] Create `requirements-dev.txt` for development: + - `pytest>=7.0.0` + - `pytest-asyncio>=0.21.0` + - `black>=23.0.0` + - `flake8>=6.0.0` + - `mypy>=1.0.0` + +2. **Database Layer** + - [ ] Create SQLAlchemy models: + - `User` (vk_id, username, created_at, referrer_id) + - `Balance` (user_id, tokens, updated_at) + - `Dialog` (id, user_id, messages, created_at) + - `Referral` (referrer_id, referred_id, bonus_given) + - [ ] Create repository classes for data access + - [ ] Implement migration system + +3. **Services Layer** + - [ ] Create `APIGatewayService`: + - `chat_completion()` - Send chat requests + - `get_user_balance()` - Check token balance + - `add_tokens()` - Add tokens to user + - `get_conversation_history()` - Fetch history + - [ ] Create `DatabaseService`: + - `get_or_create_user()` - User management + - `get_user_balance()` - Balance queries + - `deduct_tokens()` - Token deduction + - `save_message()` - Conversation history + - [ ] Create `PaymentService`: + - `create_payment_link()` - Generate VK Pay links + - `handle_payment_notification()` - Process webhooks + +4. **Bot Core** + - [ ] Create `bot_run.py` main entry point + - [ ] Implement basic command handlers: + - `/start` - Welcome message with main menu + - `/help` - Help information + - `/balance` - Show token balance + - [ ] Create main menu keyboard with buttons: + - 💬 Chat with GPT + - 💰 Balance + - ⚙️ Settings + +5. **GPT Chat Router** + - [ ] Implement conversation state management + - [ ] Create message handler for GPT chat + - [ ] Add balance checking before processing + - [ ] Implement token deduction after response + - [ ] Add error handling for API failures + +6. **Testing** + - [ ] Write unit tests for services + - [ ] Write integration tests for routers + - [ ] Create mock VK API for testing + - [ ] Test with real VK community (development) + +**Deliverables:** +- Working Python bot with GPT chat +- Database layer with migrations +- API Gateway integration +- Unit and integration tests +- Development documentation + +**Minimal Example (bot/bot_run.py):** +```python +from vkbottle.bot import Bot +from vkbottle import Keyboard, KeyboardButtonColor, Text +import os +from dotenv import load_dotenv + +load_dotenv() + +bot = Bot(token=os.getenv("VK_GROUP_TOKEN")) + +@bot.on.message(text="/start") +async def start_handler(message): + keyboard = ( + Keyboard() + .add(Text("💬 Chat with GPT"), color=KeyboardButtonColor.PRIMARY) + .row() + .add(Text("💰 Balance"), color=KeyboardButtonColor.SECONDARY) + ) + + await message.answer( + "Welcome to Deep Assistant VK Bot!\n\n" + "I can help you with:\n" + "• Chat with multiple AI models (GPT-4, Claude, etc.)\n" + "• Generate images\n" + "• And more!\n\n" + "Choose an option below:", + keyboard=keyboard.get_json() + ) + +bot.run_forever() +``` + +--- + +### Phase 3: JavaScript Bot Core (Week 4-5) + +**Objective:** Implement equivalent JavaScript bot with feature parity to Python version + +#### Tasks + +1. **Setup JavaScript Environment** + - [ ] Create `package.json` with dependencies: + - `node-vk-bot-api` + - `axios` + - `redis` + - `dotenv` + - `pino` (logging) + - [ ] Create `package.json` dev dependencies: + - `jest` + - `eslint` + - `nodemon` + - `@types/node` (if using TypeScript) + +2. **Database Layer** + - [ ] Set up Redis connection + - [ ] Create data access functions: + - User management + - Balance tracking + - Conversation history + - Referral tracking + - [ ] Implement Redis caching strategy + +3. **Services Layer** + - [ ] Create `apiGatewayService.js`: + - Mirror Python APIGatewayService functionality + - Implement HTTP client with axios + - Add retry logic for failures + - [ ] Create `databaseService.js`: + - Redis operations + - Data serialization/deserialization + - [ ] Create `paymentService.js`: + - VK Pay integration + - Webhook handling + +4. **Bot Core** + - [ ] Create `index.js` main entry point + - [ ] Implement command handlers: + - `/start`, `/help`, `/balance` + - [ ] Create keyboard layouts + - [ ] Set up middleware chain + +5. **GPT Chat Router** + - [ ] Implement conversation state with Redis + - [ ] Create message handler + - [ ] Add balance checking + - [ ] Implement token deduction + - [ ] Error handling + +6. **Testing** + - [ ] Write Jest tests for services + - [ ] Write integration tests for routers + - [ ] Create mock VK API + - [ ] Test with development community + +**Deliverables:** +- Working JavaScript bot with GPT chat +- Redis integration for state management +- API Gateway integration +- Jest tests +- Feature parity with Python implementation + +**Minimal Example (js/src/index.js):** +```javascript +const VkBot = require('node-vk-bot-api'); +const { Keyboard } = require('node-vk-bot-api'); +require('dotenv').config(); + +const bot = new VkBot(process.env.VK_GROUP_TOKEN); + +bot.command('/start', async (ctx) => { + const keyboard = Keyboard.builder() + .textButton({ label: '💬 Chat with GPT', color: Keyboard.PRIMARY_COLOR }) + .row() + .textButton({ label: '💰 Balance', color: Keyboard.SECONDARY_COLOR }) + .build(); + + await ctx.reply( + 'Welcome to Deep Assistant VK Bot!\n\n' + + 'I can help you with:\n' + + '• Chat with multiple AI models (GPT-4, Claude, etc.)\n' + + '• Generate images\n' + + '• And more!\n\n' + + 'Choose an option below:', + null, + keyboard + ); +}); + +bot.startPolling(); +console.log('VK Bot is running...'); +``` + +--- + +### Phase 4: Advanced Features (Week 6-7) + +**Objective:** Add image generation, payment processing, and referral system + +#### Tasks - Python Implementation + +1. **Image Generation Router** + - [ ] Implement `/imagine` command + - [ ] Add image upload to VK + - [ ] Implement image editing commands: + - `/edit` - Edit image with prompt + - `/upscale` - Upscale image + - `/rembg` - Remove background + - [ ] Add balance checking (100 tokens per image) + +2. **Payment Router** + - [ ] Implement `/buy` command with token packages + - [ ] Create VK Pay payment links + - [ ] Set up webhook endpoint for payment notifications + - [ ] Implement payment verification + - [ ] Add tokens to user balance after successful payment + +3. **Referral Router** + - [ ] Implement `/referral` command + - [ ] Generate referral links + - [ ] Track referrals in database + - [ ] Award bonus tokens (referrer + referred user) + - [ ] Show referral statistics + +4. **Settings Router** + - [ ] Implement `/settings` command + - [ ] Add model selection (GPT-4, Claude, etc.) + - [ ] Add language selection (EN/RU) + - [ ] Add conversation history toggle + - [ ] Persist user preferences + +#### Tasks - JavaScript Implementation + +- [ ] Implement all features above in JavaScript +- [ ] Ensure feature parity with Python version +- [ ] Write tests for all new features + +**Deliverables:** +- Image generation functionality +- Payment processing with VK Pay +- Referral system +- User settings management +- Tests for all features + +--- + +### Phase 5: Deployment & DevOps (Week 8) + +**Objective:** Containerize applications and set up production deployment + +#### Tasks + +1. **Docker Configuration** + - [ ] Create `Dockerfile` for Python bot: + ```dockerfile + FROM python:3.10-slim + WORKDIR /app + COPY requirements.txt . + RUN pip install --no-cache-dir -r requirements.txt + COPY bot/ ./bot/ + COPY services/ ./services/ + COPY db/ ./db/ + CMD ["python", "-m", "bot.bot_run"] + ``` + - [ ] Create `Dockerfile.js` for JavaScript bot + - [ ] Create `docker-compose.yml` for full stack: + - Python bot service + - JavaScript bot service + - Redis service + - Shared network + - Volume mounts + +2. **CI/CD Pipeline** + - [ ] Create `.github/workflows/python-tests.yml`: + - Run pytest on pull requests + - Check code style with black/flake8 + - Type checking with mypy + - [ ] Create `.github/workflows/js-tests.yml`: + - Run jest on pull requests + - Lint with eslint + - [ ] Create `.github/workflows/docker-build.yml`: + - Build Docker images on main branch + - Push to GitHub Container Registry + +3. **Production Deployment** + - [ ] Set up production VK community + - [ ] Configure production environment variables + - [ ] Deploy Docker containers + - [ ] Set up reverse proxy (nginx) if needed + - [ ] Configure SSL/TLS certificates + - [ ] Set up webhook endpoint for payments + +4. **Monitoring & Logging** + - [ ] Configure structured logging (JSON format) + - [ ] Set up log rotation + - [ ] Add health check endpoints + - [ ] Monitor bot uptime + - [ ] Track error rates and API latency + +**Deliverables:** +- Docker images for both implementations +- CI/CD pipelines +- Production deployment guide +- Monitoring setup + +--- + +### Phase 6: Testing & Quality Assurance (Week 9) + +**Objective:** Comprehensive testing and bug fixing + +#### Tasks + +1. **Functional Testing** + - [ ] Test all commands with real VK community + - [ ] Test GPT chat with various models + - [ ] Test image generation and editing + - [ ] Test payment flow (with VK test environment) + - [ ] Test referral system + - [ ] Test error handling and edge cases + +2. **Performance Testing** + - [ ] Load test with multiple concurrent users + - [ ] Measure API Gateway latency + - [ ] Test database performance + - [ ] Optimize slow queries + - [ ] Profile memory usage + +3. **Security Testing** + - [ ] Test authentication and authorization + - [ ] Verify payment webhook signatures + - [ ] Test rate limiting + - [ ] Check for SQL injection vulnerabilities + - [ ] Verify sensitive data is not logged + +4. **User Acceptance Testing** + - [ ] Beta test with small group of users + - [ ] Gather feedback on UX + - [ ] Identify and fix bugs + - [ ] Refine error messages + +**Deliverables:** +- Test reports +- Bug fixes +- Performance optimizations +- Security audit results + +--- + +### Phase 7: Documentation & Launch (Week 10) + +**Objective:** Complete documentation and public launch + +#### Tasks + +1. **User Documentation** + - [ ] Create user guide with screenshots + - [ ] Document all commands and features + - [ ] Create FAQ section + - [ ] Add troubleshooting guide + - [ ] Create video tutorial (optional) + +2. **Developer Documentation** + - [ ] Complete API documentation + - [ ] Document database schema + - [ ] Add code examples + - [ ] Document deployment process + - [ ] Add troubleshooting guide for common issues + +3. **Launch Preparation** + - [ ] Final security review + - [ ] Load testing with expected user count + - [ ] Set up support channels + - [ ] Prepare announcement materials + - [ ] Create marketing materials (if needed) + +4. **Public Launch** + - [ ] Announce on VK community + - [ ] Post on Telegram channel + - [ ] Update master-plan README with link to vk-bot repository + - [ ] Monitor for issues and respond quickly + +**Deliverables:** +- Complete documentation +- Public launch +- Support infrastructure + +--- + +## Success Metrics + +### Technical Metrics + +- **Uptime**: >99.5% availability +- **Response Time**: <500ms average (excluding LLM processing) +- **Error Rate**: <1% of requests +- **Test Coverage**: >80% code coverage + +### User Metrics + +- **Active Users**: Track daily/weekly/monthly active users +- **Retention**: Monitor user retention rates +- **Feature Usage**: Track which features are most popular +- **User Satisfaction**: Gather feedback and ratings + +### Business Metrics + +- **Token Purchases**: Track revenue from token sales +- **Referrals**: Track successful referral conversions +- **API Costs**: Monitor API Gateway usage costs +- **Cost per User**: Calculate operating costs per user + +--- + +## Risk Management + +### Technical Risks + +| Risk | Likelihood | Impact | Mitigation | +|------|------------|--------|------------| +| VK API changes | Medium | High | Monitor VK API changelog, implement API versioning | +| API Gateway downtime | Low | High | Implement retry logic, failover mechanisms | +| Database corruption | Low | High | Regular backups, use WAL mode for SQLite | +| Security breach | Low | Critical | Regular security audits, follow security best practices | + +### Operational Risks + +| Risk | Likelihood | Impact | Mitigation | +|------|------------|--------|------------| +| High API costs | Medium | Medium | Implement rate limiting, monitor usage | +| VK policy violation | Low | Critical | Review VK bot policies, ensure compliance | +| User data leak | Low | Critical | Encrypt sensitive data, limit data retention | +| Spam/abuse | Medium | Medium | Implement rate limiting, abuse detection | + +--- + +## Timeline Summary + +| Phase | Duration | Key Deliverables | +|-------|----------|------------------| +| 1. Repository Setup | Week 1 | Repository structure, documentation | +| 2. Python Bot Core | Weeks 2-3 | Working Python bot with GPT chat | +| 3. JavaScript Bot Core | Weeks 4-5 | Working JavaScript bot with feature parity | +| 4. Advanced Features | Weeks 6-7 | Images, payments, referrals | +| 5. Deployment & DevOps | Week 8 | Docker, CI/CD, production deployment | +| 6. Testing & QA | Week 9 | Comprehensive testing, bug fixes | +| 7. Documentation & Launch | Week 10 | Complete docs, public launch | + +**Total Estimated Time:** 10 weeks (2.5 months) + +--- + +## Dependencies + +### External Dependencies + +- **VK Platform**: VK API availability and stability +- **API Gateway**: Existing API Gateway service must be operational +- **LLM Providers**: OpenAI, Anthropic, etc. availability via API Gateway +- **VK Pay**: Merchant account approval and webhook setup + +### Internal Dependencies + +- **API Gateway**: Must support required endpoints +- **Infrastructure**: Hosting environment and domain setup +- **Team Resources**: Development and testing resources + +--- + +## Next Steps + +### Immediate Actions (This PR) + +1. ✅ Create VK Bot architecture document +2. ✅ Update master-plan README with VK bot reference +3. [ ] Create minimal working examples (Python + JavaScript) +4. [ ] Update PR description with implementation plan +5. [ ] Get feedback from maintainers on approach + +### Post-PR Actions + +1. Create `deep-assistant/vk-bot` repository +2. Begin Phase 1: Repository Setup +3. Start Phase 2: Python Bot Core development +4. Continue following implementation plan phases + +--- + +## Questions for Maintainers + +Before proceeding with full implementation, please provide feedback on: + +1. **Repository Structure**: Should this be a new repository or integrated into existing GPTutor repo? +2. **Feature Scope**: Are all proposed features (GPT chat, images, payments, referrals) desired for v1.0? +3. **Timeline**: Is the 10-week timeline acceptable, or should we prioritize differently? +4. **Deployment**: Any specific hosting/deployment preferences? +5. **Payment Integration**: Should we use VK Donut, VK Pay, or both? + +--- + +## References + +- [VK Bot API Documentation](https://vk-api.readthedocs.io/) +- [vkbottle Framework](https://github.com/vkbottle/vkbottle) +- [node-vk-bot-api Framework](https://github.com/node-vk-bot-api/node-vk-bot-api) +- [Telegram Bot Repository](https://github.com/deep-assistant/telegram-bot) (reference implementation) +- [API Gateway Repository](https://github.com/deep-assistant/api-gateway) +- [GPTutor Repository](https://github.com/deep-assistant/GPTutor) (existing VK mini app) + +--- + +*This implementation plan is a living document and will be updated as the project progresses.* diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..fcf1987 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,301 @@ +# VK Bot Examples + +This directory contains minimal working examples of VK bots in both Python and JavaScript, demonstrating the core concepts and architecture patterns for the full VK bot implementation. + +## Overview + +These examples showcase how to build a VK bot that integrates with the Deep Assistant ecosystem, specifically: +- Handling VK messages and commands +- Creating interactive keyboard layouts +- Managing conversation state +- Integrating with the API Gateway for LLM functionality +- Checking user token balances + +## Available Examples + +### 1. Python Bot (`python-bot/`) + +**Framework:** [vkbottle](https://github.com/vkbottle/vkbottle) + +A feature-complete example demonstrating: +- Command handling with decorators +- State management using vkbottle's built-in system +- Async/await patterns with aiohttp +- Clean service architecture + +**Quick Start:** +```bash +cd python-bot +pip install -r requirements.txt +cp .env.example .env +# Edit .env with your tokens +python bot.py +``` + +See [python-bot/README.md](./python-bot/README.md) for detailed instructions. + +### 2. JavaScript Bot (`javascript-bot/`) + +**Framework:** [node-vk-bot-api](https://github.com/node-vk-bot-api/node-vk-bot-api) + +An equivalent implementation in Node.js demonstrating: +- Command and message handling +- In-memory state management (Map-based) +- Async/await with axios +- Modular service design + +**Quick Start:** +```bash +cd javascript-bot +npm install +cp .env.example .env +# Edit .env with your tokens +npm start +``` + +See [javascript-bot/README.md](./javascript-bot/README.md) for detailed instructions. + +## Features Demonstrated + +Both examples implement the same features to show feature parity: + +- ✅ **Basic Commands** + - `/start` - Welcome message with main menu + - `/help` - Help information + - `/balance` - Check token balance + - `/models` - List available AI models + +- ✅ **Interactive Keyboards** + - Main menu with action buttons + - Context-sensitive keyboards + - Cancel functionality + +- ✅ **Conversation State** + - Chat mode for continuous conversations + - State persistence across messages + - State cleanup on cancel + +- ✅ **API Gateway Integration** + - Chat completions with GPT models + - User balance checking + - Error handling and retries + +- ✅ **User Experience** + - Friendly error messages + - Balance warnings + - Token usage tracking + +## Architecture Comparison + +### Python (vkbottle) + +```python +@bot.on.message(text="/start") +async def start_handler(message: Message): + await message.answer("Welcome!", keyboard=keyboard.get_json()) +``` + +**Pros:** +- Clean decorator-based routing +- Built-in state management +- Type hints with Pydantic +- Native async support + +**Cons:** +- Requires Python 3.10+ +- Larger memory footprint +- Slower cold start + +### JavaScript (node-vk-bot-api) + +```javascript +bot.command('/start', async (ctx) => { + await ctx.reply('Welcome!', null, keyboard); +}); +``` + +**Pros:** +- Fast startup and execution +- Smaller memory footprint +- Familiar syntax for JS developers +- Easy deployment with Node.js + +**Cons:** +- Manual state management +- No built-in typing system +- More boilerplate code + +## What's Not Included + +These are minimal examples. For production, you would add: + +- ❌ Database layer (SQLite, PostgreSQL, MongoDB) +- ❌ Persistent state storage (Redis) +- ❌ Payment integration (VK Pay/Donut) +- ❌ Image generation functionality +- ❌ Referral system +- ❌ Settings management +- ❌ Comprehensive error handling +- ❌ Logging and monitoring +- ❌ Rate limiting +- ❌ Unit and integration tests +- ❌ Docker deployment +- ❌ CI/CD pipelines + +See the [VK-BOT-ARCHITECTURE.md](../VK-BOT-ARCHITECTURE.md) and [VK-BOT-IMPLEMENTATION-PLAN.md](../VK-BOT-IMPLEMENTATION-PLAN.md) for the complete production architecture. + +## Testing the Examples + +### Without API Gateway + +You can test basic bot functionality without the API Gateway: + +1. Set only `VK_GROUP_TOKEN` in `.env` +2. Run the bot +3. Test commands: `/start`, `/help`, `/models` +4. Test keyboard navigation + +The GPT chat feature will show a friendly error if API Gateway is not configured. + +### With API Gateway + +For full functionality including GPT chat: + +1. Ensure the API Gateway is running +2. Set `API_GATEWAY_TOKEN` in `.env` +3. Ensure your user has tokens in the API Gateway +4. Test GPT chat functionality + +### Testing Checklist + +- [ ] Bot responds to `/start` with main menu +- [ ] Help button shows help information +- [ ] All keyboard buttons work +- [ ] Conversation state persists across messages +- [ ] Cancel button returns to main menu +- [ ] Balance check works (if API Gateway configured) +- [ ] GPT chat works (if API Gateway configured) +- [ ] Errors are handled gracefully + +## Prerequisites + +### VK Platform Setup + +1. **Create VK Community** (if you don't have one) + - Go to https://vk.com/groups + - Create a new community/group + +2. **Enable Community Messages** + - Go to Community Settings → Messages + - Enable "Community Messages" + - Configure "Bot Settings" as needed + +3. **Enable Long Poll API** + - Go to Settings → API usage → Long Poll API + - Enable Long Poll API + - Set API version to 5.131 or higher + +4. **Get Access Token** + - Go to Settings → API usage → Access tokens + - Create a token with `messages` scope + - Copy the token (starts with `vk1.a.`) + +### API Gateway Setup (Optional) + +If you want to test the full functionality: + +1. Deploy the [api-gateway](https://github.com/deep-assistant/api-gateway) +2. Obtain a master token for authentication +3. Ensure the gateway is accessible from your network + +## Environment Variables + +Both examples use the same environment variables: + +```bash +# Required +VK_GROUP_TOKEN=vk1.a.your_token_here + +# Optional (for chat functionality) +API_GATEWAY_URL=https://api.deep-assistant.com +API_GATEWAY_TOKEN=your_gateway_token_here +``` + +## Next Steps + +### Moving to Production + +1. **Choose an Implementation** + - Start with Python or JavaScript based on your preference + - Or maintain both for redundancy + +2. **Add Database Layer** + - Python: SQLAlchemy with SQLite/PostgreSQL + - JavaScript: Redis or MongoDB + +3. **Add Missing Features** + - Image generation + - Payment processing + - Referral system + - Settings management + +4. **Deploy** + - Containerize with Docker + - Set up CI/CD + - Deploy to production + +5. **Monitor** + - Add logging (Pino, Winston) + - Set up error tracking + - Monitor performance + +### Creating the Full Repository + +These examples are proof-of-concepts. To create the full `vk-bot` repository: + +1. Follow the [VK-BOT-IMPLEMENTATION-PLAN.md](../VK-BOT-IMPLEMENTATION-PLAN.md) +2. Set up proper project structure +3. Add all production features +4. Write comprehensive tests +5. Set up deployment infrastructure + +## Contributing + +These examples are part of the [master-plan](https://github.com/deep-assistant/master-plan) repository and demonstrate the approach for issue [#1](https://github.com/deep-assistant/master-plan/issues/1). + +To contribute: +1. Test the examples and report issues +2. Suggest improvements +3. Help with documentation +4. Contribute to the full vk-bot implementation + +## Resources + +### Documentation +- [VK API Documentation](https://dev.vk.com/api/bots) +- [vkbottle Documentation](https://vkbottle.readthedocs.io/) +- [node-vk-bot-api Documentation](https://github.com/node-vk-bot-api/node-vk-bot-api) + +### Related Repositories +- [telegram-bot](https://github.com/deep-assistant/telegram-bot) - Reference implementation +- [api-gateway](https://github.com/deep-assistant/api-gateway) - Backend service +- [GPTutor](https://github.com/deep-assistant/GPTutor) - Existing VK mini app + +### Architecture Documents +- [VK-BOT-ARCHITECTURE.md](../VK-BOT-ARCHITECTURE.md) - Full architecture specification +- [VK-BOT-IMPLEMENTATION-PLAN.md](../VK-BOT-IMPLEMENTATION-PLAN.md) - 10-week implementation plan + +## License + +These examples are released under the Unlicense (Public Domain). Feel free to use them however you like. + +## Support + +For questions or issues: +- Open an issue on [master-plan](https://github.com/deep-assistant/master-plan/issues) +- Check existing [discussions](https://github.com/deep-assistant/master-plan/discussions) +- Review the architecture documentation + +--- + +**Note:** These are demonstration examples intended to be moved to a dedicated `vk-bot` repository once the full implementation begins. diff --git a/examples/javascript-bot/.env.example b/examples/javascript-bot/.env.example new file mode 100644 index 0000000..a9367f7 --- /dev/null +++ b/examples/javascript-bot/.env.example @@ -0,0 +1,9 @@ +# VK Configuration +VK_GROUP_TOKEN=vk1.a.your_vk_group_token_here + +# VK Confirmation Token (only needed for webhook mode) +# VK_CONFIRMATION_TOKEN=your_confirmation_token + +# API Gateway Configuration (optional for basic testing) +API_GATEWAY_URL=https://api.deep-assistant.com +API_GATEWAY_TOKEN=your_api_gateway_master_token_here diff --git a/examples/javascript-bot/README.md b/examples/javascript-bot/README.md new file mode 100644 index 0000000..6ed6f9b --- /dev/null +++ b/examples/javascript-bot/README.md @@ -0,0 +1,192 @@ +# JavaScript VK Bot Example + +This is a minimal working example of a VK bot implemented in JavaScript/Node.js using the `node-vk-bot-api` framework. + +## Features + +- ✅ Command handling (`/start`, `/help`, `/balance`, `/models`) +- ✅ Interactive keyboard layouts +- ✅ Conversation state management (in-memory) +- ✅ API Gateway integration for GPT chat +- ✅ User balance checking +- ✅ Error handling + +## Prerequisites + +- Node.js 18 or higher +- npm or yarn +- VK Community with: + - Community Messages enabled + - Long Poll API enabled + - Access Token with `messages` scope + +## Installation + +1. Clone this repository or copy the example files + +2. Install dependencies: + ```bash + npm install + ``` + +3. Configure environment variables: + ```bash + cp .env.example .env + # Edit .env with your VK token and API Gateway credentials + ``` + +## Configuration + +### Required Environment Variables + +- `VK_GROUP_TOKEN` - Your VK community access token + +### Optional Environment Variables + +- `API_GATEWAY_URL` - API Gateway base URL (default: https://api.deep-assistant.com) +- `API_GATEWAY_TOKEN` - API Gateway authentication token (required for chat functionality) +- `VK_CONFIRMATION_TOKEN` - Confirmation token for webhook mode (only if using webhooks) + +### Getting VK Access Token + +1. Create a VK Community (if you don't have one) +2. Go to Community Settings → Messages +3. Enable "Community Messages" +4. Go to Settings → API usage → Access tokens +5. Create a token with `messages` scope +6. Copy the token to your `.env` file + +## Usage + +### Development Mode + +Run with auto-reload on file changes: + +```bash +npm run dev +``` + +### Production Mode + +Run the bot: + +```bash +npm start +``` + +The bot will start polling for messages. Open your VK community and send a message to test it. + +## Available Commands + +- `/start` - Start the bot and show main menu +- `/help` - Display help information +- `/balance` - Check token balance (requires API Gateway) +- `/models` - List available AI models + +## Interactive Buttons + +- 💬 **Chat with GPT** - Start a conversation with AI (requires API Gateway) +- 🎨 **Generate Image** - Generate images (placeholder) +- 💰 **Balance** - Check your token balance +- ⚙️ **Settings** - Configure bot preferences (placeholder) +- ℹ️ **Help** - Show help message + +## Testing Without API Gateway + +You can test the basic bot functionality (commands, keyboards, navigation) without setting up the API Gateway. The GPT chat feature will show an error message if the API Gateway is not configured. + +## Architecture + +``` +VK User → VK Community → Bot (node-vk-bot-api) → API Gateway → LLM Providers +``` + +### Components + +- **Bot Core**: Handles VK API interactions using node-vk-bot-api +- **APIGatewayService**: Communicates with API Gateway for LLM requests +- **State Management**: In-memory Map for conversation state (use Redis in production) +- **Keyboard Layouts**: Provides interactive UI with buttons + +## State Management + +This example uses an in-memory Map to store user conversation states. This means: +- ✅ Simple and works for testing +- ❌ States are lost on bot restart +- ❌ Not suitable for production with multiple instances + +For production, use Redis: +```javascript +const redis = require('redis'); +const client = redis.createClient(); + +async function setUserState(userId, state) { + await client.set(`state:${userId}`, state); +} + +async function getUserState(userId) { + return await client.get(`state:${userId}`); +} +``` + +## Next Steps + +This example demonstrates the core concepts. For a production-ready implementation, you would add: + +- Redis for state management +- Database layer for user data and conversation history +- Payment integration (VK Pay/Donut) +- Image generation functionality +- Referral system +- Settings management +- Comprehensive error handling +- Logging with Pino +- Rate limiting +- Docker deployment + +See [VK-BOT-ARCHITECTURE.md](../../VK-BOT-ARCHITECTURE.md) for the complete architecture and [VK-BOT-IMPLEMENTATION-PLAN.md](../../VK-BOT-IMPLEMENTATION-PLAN.md) for the full implementation roadmap. + +## Troubleshooting + +### Bot doesn't respond + +- Verify Community Messages are enabled +- Check Long Poll API is active +- Verify access token has `messages` scope +- Check console for error messages + +### Chat with GPT doesn't work + +- Verify API_GATEWAY_TOKEN is set correctly +- Check API Gateway is accessible from your network +- Verify your user has tokens in the API Gateway + +### Module not found errors + +- Run `npm install` to install dependencies +- Verify Node.js version is 18 or higher + +## Deployment Options + +### Polling Mode (Default) + +The bot polls VK servers for new messages. Simple to set up, works everywhere. + +### Webhook Mode + +For production, use webhooks: + +1. Set up a public HTTPS endpoint +2. Configure webhook in VK Community Settings +3. Set `VK_CONFIRMATION_TOKEN` in `.env` +4. Modify bot.js to use webhook mode: + ```javascript + bot.startWebhook({ + path: '/webhook', + port: process.env.PORT || 3000 + }); + ``` + +## License + +Unlicense (Public Domain) diff --git a/examples/javascript-bot/bot.js b/examples/javascript-bot/bot.js new file mode 100644 index 0000000..b0b6c81 --- /dev/null +++ b/examples/javascript-bot/bot.js @@ -0,0 +1,476 @@ +#!/usr/bin/env node +/** + * Minimal VK Bot Example (JavaScript/Node.js) + * + * This is a proof-of-concept VK bot that demonstrates: + * - Basic command handling (/start, /help) + * - Keyboard layouts + * - Integration with API Gateway for GPT chat + * - User balance checking + * + * This example is intended to be moved to the vk-bot repository. + * + * Dependencies: + * npm install node-vk-bot-api axios dotenv + * + * Environment Variables: + * VK_GROUP_TOKEN - VK community access token + * API_GATEWAY_URL - API Gateway base URL + * API_GATEWAY_TOKEN - API Gateway authentication token + */ + +const VkBot = require('node-vk-bot-api'); +const axios = require('axios'); +require('dotenv').config(); + +// Configuration +const VK_GROUP_TOKEN = process.env.VK_GROUP_TOKEN; +const API_GATEWAY_URL = process.env.API_GATEWAY_URL || 'https://api.deep-assistant.com'; +const API_GATEWAY_TOKEN = process.env.API_GATEWAY_TOKEN; + +if (!VK_GROUP_TOKEN) { + console.error('❌ VK_GROUP_TOKEN environment variable is required'); + process.exit(1); +} + +// Initialize bot +const bot = new VkBot({ + token: VK_GROUP_TOKEN, + confirmation: process.env.VK_CONFIRMATION_TOKEN // For webhook mode +}); + +// In-memory state storage (use Redis in production) +const userStates = new Map(); + +// API Gateway Service +class APIGatewayService { + constructor(baseUrl, token) { + this.baseUrl = baseUrl; + this.token = token; + this.client = axios.create({ + baseURL: baseUrl, + headers: { + 'Authorization': `Bearer ${token}`, + 'Content-Type': 'application/json' + }, + timeout: 60000 + }); + } + + async chatCompletion(userId, message, model = 'gpt-3.5-turbo') { + try { + const response = await this.client.post('/v1/chat/completions', { + model: model, + messages: [{ role: 'user', content: message }], + user_id: String(userId) + }); + return response.data; + } catch (error) { + if (error.response) { + throw new Error(`API Gateway error: ${error.response.status} - ${error.response.data}`); + } + throw new Error(`API Gateway request failed: ${error.message}`); + } + } + + async getUserBalance(userId) { + try { + const response = await this.client.get(`/tokens/${userId}`); + return response.data.balance || 0; + } catch (error) { + // If user doesn't exist, return 0 + if (error.response && error.response.status === 404) { + return 0; + } + console.error(`Error fetching balance: ${error.message}`); + return 0; + } + } +} + +// Initialize API Gateway service +const apiGateway = API_GATEWAY_TOKEN + ? new APIGatewayService(API_GATEWAY_URL, API_GATEWAY_TOKEN) + : null; + +// Keyboard Layouts +const Keyboard = VkBot.Keyboard; + +function getMainKeyboard() { + return Keyboard.keyboard([ + [ + Keyboard.textButton({ + label: '💬 Chat with GPT', + color: Keyboard.PRIMARY_COLOR + }) + ], + [ + Keyboard.textButton({ + label: '🎨 Generate Image', + color: Keyboard.POSITIVE_COLOR + }) + ], + [ + Keyboard.textButton({ + label: '💰 Balance', + color: Keyboard.SECONDARY_COLOR + }), + Keyboard.textButton({ + label: '⚙️ Settings', + color: Keyboard.SECONDARY_COLOR + }) + ], + [ + Keyboard.textButton({ + label: 'ℹ️ Help', + color: Keyboard.SECONDARY_COLOR + }) + ] + ]); +} + +function getCancelKeyboard() { + return Keyboard.keyboard([ + [ + Keyboard.textButton({ + label: '❌ Cancel', + color: Keyboard.NEGATIVE_COLOR + }) + ] + ]); +} + +// Helper functions +function setUserState(userId, state) { + userStates.set(userId, state); +} + +function getUserState(userId) { + return userStates.get(userId) || null; +} + +function clearUserState(userId) { + userStates.delete(userId); +} + +// Command Handlers + +// /start command +bot.command('/start', async (ctx) => { + await ctx.reply( + '👋 Welcome to Deep Assistant VK Bot!\n\n' + + 'I\'m your AI assistant powered by multiple language models. ' + + 'I can help you with:\n\n' + + '💬 Chat with AI (GPT-4, Claude, Gemini, etc.)\n' + + '🎨 Generate images with DALL-E\n' + + '🔊 Transcribe audio messages\n' + + '📝 And much more!\n\n' + + 'Choose an option below to get started:', + null, + getMainKeyboard() + ); +}); + +// /help command +bot.command('/help', async (ctx) => { + await ctx.reply( + '📚 Help & Commands\n\n' + + 'Available commands:\n' + + '/start - Start the bot\n' + + '/help - Show this help message\n' + + '/balance - Check your token balance\n' + + '/models - List available AI models\n\n' + + 'Quick Actions:\n' + + '💬 Chat with GPT - Start a conversation with AI\n' + + '🎨 Generate Image - Create images from text\n' + + '💰 Balance - View your token balance\n' + + '⚙️ Settings - Configure bot preferences\n\n' + + 'Need more help? Contact support or visit our documentation.', + null, + getMainKeyboard() + ); +}); + +// /balance command +bot.command('/balance', async (ctx) => { + if (!apiGateway) { + await ctx.reply( + '⚠️ API Gateway is not configured. Please set up environment variables.', + null, + getMainKeyboard() + ); + return; + } + + try { + const balance = await apiGateway.getUserBalance(ctx.message.from_id); + const lowBalance = balance < 100; + + await ctx.reply( + `💰 Your Balance\n\n` + + `Current balance: ${balance} tokens\n\n` + + `Tokens are used for:\n` + + `• AI chat messages (~10-100 tokens per message)\n` + + `• Image generation (~100 tokens per image)\n` + + `• Audio transcription (~50 tokens per minute)\n\n` + + (lowBalance + ? '⚠️ Low balance! Consider purchasing more tokens.' + : '✅ You have enough tokens to continue.' + ), + null, + getMainKeyboard() + ); + } catch (error) { + await ctx.reply( + `❌ Error fetching balance: ${error.message}`, + null, + getMainKeyboard() + ); + } +}); + +// /models command +bot.command('/models', async (ctx) => { + await ctx.reply( + '🤖 Available AI Models\n\n' + + 'Chat Models:\n' + + '• GPT-4 - Most capable OpenAI model\n' + + '• GPT-3.5 Turbo - Fast and efficient\n' + + '• Claude 3 Opus - Anthropic\'s best model\n' + + '• Claude 3 Sonnet - Balanced performance\n' + + '• Gemini Pro - Google\'s AI model\n' + + '• Llama 3 - Meta\'s open model\n\n' + + 'Image Models:\n' + + '• DALL-E 3 - High-quality image generation\n' + + '• Stable Diffusion - Open-source alternative\n\n' + + 'Use /settings to change your default model.', + null, + getMainKeyboard() + ); +}); + +// Button handlers +bot.on((ctx) => { + const text = ctx.message.text; + + // Help button + if (text === 'ℹ️ Help') { + return ctx.reply( + '📚 Help & Commands\n\n' + + 'Available commands:\n' + + '/start - Start the bot\n' + + '/help - Show this help message\n' + + '/balance - Check your token balance\n' + + '/models - List available AI models\n\n' + + 'Quick Actions:\n' + + '💬 Chat with GPT - Start a conversation with AI\n' + + '🎨 Generate Image - Create images from text\n' + + '💰 Balance - View your token balance\n' + + '⚙️ Settings - Configure bot preferences\n\n' + + 'Need more help? Contact support or visit our documentation.', + null, + getMainKeyboard() + ); + } + + // Balance button + if (text === '💰 Balance') { + return handleBalanceButton(ctx); + } + + // Chat with GPT button + if (text === '💬 Chat with GPT') { + return handleChatStart(ctx); + } + + // Cancel button + if (text === '❌ Cancel') { + return handleCancel(ctx); + } + + // Generate Image button + if (text === '🎨 Generate Image') { + return ctx.reply( + '🎨 Image Generation\n\n' + + 'This feature will be available soon!\n\n' + + 'You\'ll be able to generate images by describing what you want to see.', + null, + getMainKeyboard() + ); + } + + // Settings button + if (text === '⚙️ Settings') { + return ctx.reply( + '⚙️ Settings\n\n' + + 'Settings panel will be available soon!\n\n' + + 'You\'ll be able to:\n' + + '• Choose your preferred AI model\n' + + '• Set language preference\n' + + '• Configure conversation history\n' + + '• And more!', + null, + getMainKeyboard() + ); + } + + // Handle chat messages in conversation state + const state = getUserState(ctx.message.from_id); + if (state === 'WAITING_FOR_MESSAGE') { + return handleChatMessage(ctx); + } + + // Fallback for unknown messages + return ctx.reply( + '🤔 I didn\'t understand that command.\n\n' + + 'Use the buttons below or type /help to see available commands.', + null, + getMainKeyboard() + ); +}); + +// Handler functions +async function handleBalanceButton(ctx) { + if (!apiGateway) { + await ctx.reply( + '⚠️ API Gateway is not configured. Please set up environment variables.', + null, + getMainKeyboard() + ); + return; + } + + try { + const balance = await apiGateway.getUserBalance(ctx.message.from_id); + const lowBalance = balance < 100; + + await ctx.reply( + `💰 Your Balance\n\n` + + `Current balance: ${balance} tokens\n\n` + + `Tokens are used for:\n` + + `• AI chat messages (~10-100 tokens per message)\n` + + `• Image generation (~100 tokens per image)\n` + + `• Audio transcription (~50 tokens per minute)\n\n` + + (lowBalance + ? '⚠️ Low balance! Consider purchasing more tokens.' + : '✅ You have enough tokens to continue.' + ), + null, + getMainKeyboard() + ); + } catch (error) { + await ctx.reply( + `❌ Error fetching balance: ${error.message}`, + null, + getMainKeyboard() + ); + } +} + +async function handleChatStart(ctx) { + setUserState(ctx.message.from_id, 'WAITING_FOR_MESSAGE'); + + await ctx.reply( + '💬 Chat Mode Activated\n\n' + + 'Send me any message and I\'ll respond using AI. ' + + 'Your conversation history will be maintained.\n\n' + + 'Type \'❌ Cancel\' to return to the main menu.', + null, + getCancelKeyboard() + ); +} + +async function handleCancel(ctx) { + clearUserState(ctx.message.from_id); + + await ctx.reply( + 'Operation cancelled. Returning to main menu.', + null, + getMainKeyboard() + ); +} + +async function handleChatMessage(ctx) { + if (!apiGateway) { + await ctx.reply( + '⚠️ API Gateway is not configured.', + null, + getMainKeyboard() + ); + clearUserState(ctx.message.from_id); + return; + } + + // Check balance + try { + const balance = await apiGateway.getUserBalance(ctx.message.from_id); + if (balance < 10) { + await ctx.reply( + '⚠️ Insufficient balance. You need at least 10 tokens to send a message.\n' + + 'Use /balance to check your balance.', + null, + getMainKeyboard() + ); + clearUserState(ctx.message.from_id); + return; + } + } catch (error) { + console.error(`Error checking balance: ${error.message}`); + } + + // Send "thinking" indicator + await ctx.reply('🤔 Thinking...'); + + // Send to API Gateway + try { + const response = await apiGateway.chatCompletion( + ctx.message.from_id, + ctx.message.text, + 'gpt-3.5-turbo' + ); + + // Extract response text + const content = response.choices?.[0]?.message?.content || ''; + const tokensUsed = response.usage?.total_tokens || 0; + + if (content) { + await ctx.reply( + `${content}\n\n_Tokens used: ${tokensUsed}_`, + null, + getCancelKeyboard() + ); + } else { + await ctx.reply( + '❌ Received empty response from API.', + null, + getCancelKeyboard() + ); + } + } catch (error) { + await ctx.reply( + `❌ Error: ${error.message}\n\n` + + 'Please try again or contact support if the issue persists.', + null, + getMainKeyboard() + ); + clearUserState(ctx.message.from_id); + } +} + +// Start bot +console.log('🤖 VK Bot is starting...'); +console.log(`📡 API Gateway URL: ${API_GATEWAY_URL}`); +console.log(`🔐 API Gateway configured: ${apiGateway ? 'Yes' : 'No'}`); +console.log('✅ Bot is ready!'); + +bot.startPolling((error) => { + if (error) { + console.error('❌ Polling error:', error); + } +}); + +// Handle graceful shutdown +process.on('SIGINT', () => { + console.log('\n🛑 Shutting down bot...'); + process.exit(0); +}); diff --git a/examples/javascript-bot/package.json b/examples/javascript-bot/package.json new file mode 100644 index 0000000..9b34916 --- /dev/null +++ b/examples/javascript-bot/package.json @@ -0,0 +1,30 @@ +{ + "name": "vk-bot-example-javascript", + "version": "1.0.0", + "description": "Minimal VK Bot example using Node.js", + "main": "bot.js", + "scripts": { + "start": "node bot.js", + "dev": "nodemon bot.js" + }, + "keywords": [ + "vk", + "bot", + "vkontakte", + "ai", + "chatbot" + ], + "author": "Deep Assistant Team", + "license": "Unlicense", + "dependencies": { + "node-vk-bot-api": "^4.0.0", + "axios": "^1.6.0", + "dotenv": "^16.0.0" + }, + "devDependencies": { + "nodemon": "^3.0.0" + }, + "engines": { + "node": ">=18.0.0" + } +} diff --git a/examples/python-bot/.env.example b/examples/python-bot/.env.example new file mode 100644 index 0000000..4680521 --- /dev/null +++ b/examples/python-bot/.env.example @@ -0,0 +1,6 @@ +# VK Configuration +VK_GROUP_TOKEN=vk1.a.your_vk_group_token_here + +# API Gateway Configuration (optional for basic testing) +API_GATEWAY_URL=https://api.deep-assistant.com +API_GATEWAY_TOKEN=your_api_gateway_master_token_here diff --git a/examples/python-bot/README.md b/examples/python-bot/README.md new file mode 100644 index 0000000..c6c8139 --- /dev/null +++ b/examples/python-bot/README.md @@ -0,0 +1,137 @@ +# Python VK Bot Example + +This is a minimal working example of a VK bot implemented in Python using the `vkbottle` framework. + +## Features + +- ✅ Command handling (`/start`, `/help`, `/balance`, `/models`) +- ✅ Interactive keyboard layouts +- ✅ Conversation state management +- ✅ API Gateway integration for GPT chat +- ✅ User balance checking +- ✅ Error handling + +## Prerequisites + +- Python 3.10 or higher +- VK Community with: + - Community Messages enabled + - Long Poll API enabled + - Access Token with `messages` scope + +## Installation + +1. Clone this repository or copy the example files + +2. Install dependencies: + ```bash + pip install -r requirements.txt + ``` + +3. Configure environment variables: + ```bash + cp .env.example .env + # Edit .env with your VK token and API Gateway credentials + ``` + +## Configuration + +### Required Environment Variables + +- `VK_GROUP_TOKEN` - Your VK community access token + +### Optional Environment Variables + +- `API_GATEWAY_URL` - API Gateway base URL (default: https://api.deep-assistant.com) +- `API_GATEWAY_TOKEN` - API Gateway authentication token (required for chat functionality) + +### Getting VK Access Token + +1. Create a VK Community (if you don't have one) +2. Go to Community Settings → Messages +3. Enable "Community Messages" +4. Go to Settings → API usage → Access tokens +5. Create a token with `messages` scope +6. Copy the token to your `.env` file + +## Usage + +Run the bot: + +```bash +python bot.py +``` + +The bot will start polling for messages. Open your VK community and send a message to test it. + +## Available Commands + +- `/start` - Start the bot and show main menu +- `/help` - Display help information +- `/balance` - Check token balance (requires API Gateway) +- `/models` - List available AI models + +## Interactive Buttons + +- 💬 **Chat with GPT** - Start a conversation with AI (requires API Gateway) +- 🎨 **Generate Image** - Generate images (placeholder) +- 💰 **Balance** - Check your token balance +- ⚙️ **Settings** - Configure bot preferences (placeholder) +- ℹ️ **Help** - Show help message + +## Testing Without API Gateway + +You can test the basic bot functionality (commands, keyboards, navigation) without setting up the API Gateway. The GPT chat feature will show an error message if the API Gateway is not configured. + +## Architecture + +``` +VK User → VK Community → Bot (vkbottle) → API Gateway → LLM Providers +``` + +### Components + +- **Bot Core**: Handles VK API interactions using vkbottle +- **APIGatewayService**: Communicates with API Gateway for LLM requests +- **State Management**: Tracks conversation state using vkbottle state system +- **Keyboard Layouts**: Provides interactive UI with buttons + +## Next Steps + +This example demonstrates the core concepts. For a production-ready implementation, you would add: + +- Database layer for user data and conversation history +- Payment integration (VK Pay/Donut) +- Image generation functionality +- Referral system +- Settings management +- Comprehensive error handling +- Logging and monitoring +- Rate limiting +- Docker deployment + +See [VK-BOT-ARCHITECTURE.md](../../VK-BOT-ARCHITECTURE.md) for the complete architecture and [VK-BOT-IMPLEMENTATION-PLAN.md](../../VK-BOT-IMPLEMENTATION-PLAN.md) for the full implementation roadmap. + +## Troubleshooting + +### Bot doesn't respond + +- Verify Community Messages are enabled +- Check Long Poll API is active +- Verify access token has `messages` scope +- Check console for error messages + +### Chat with GPT doesn't work + +- Verify API_GATEWAY_TOKEN is set correctly +- Check API Gateway is accessible from your network +- Verify your user has tokens in the API Gateway + +### State errors + +- States are stored in memory and will be lost on restart +- For production, use a persistent state storage (Redis, database) + +## License + +Unlicense (Public Domain) diff --git a/examples/python-bot/bot.py b/examples/python-bot/bot.py new file mode 100644 index 0000000..a1c6fab --- /dev/null +++ b/examples/python-bot/bot.py @@ -0,0 +1,369 @@ +#!/usr/bin/env python3 +""" +Minimal VK Bot Example (Python) + +This is a proof-of-concept VK bot that demonstrates: +- Basic command handling (/start, /help) +- Keyboard layouts +- Integration with API Gateway for GPT chat +- User balance checking + +This example is intended to be moved to the vk-bot repository. + +Dependencies: + pip install vkbottle aiohttp python-dotenv + +Environment Variables: + VK_GROUP_TOKEN - VK community access token + API_GATEWAY_URL - API Gateway base URL + API_GATEWAY_TOKEN - API Gateway authentication token +""" + +import os +import asyncio +import aiohttp +from typing import Optional +from vkbottle.bot import Bot, Message +from vkbottle import Keyboard, KeyboardButtonColor, Text +from vkbottle import BaseStateGroup +from dotenv import load_dotenv + +# Load environment variables +load_dotenv() + +# Configuration +VK_GROUP_TOKEN = os.getenv("VK_GROUP_TOKEN") +API_GATEWAY_URL = os.getenv("API_GATEWAY_URL", "https://api.deep-assistant.com") +API_GATEWAY_TOKEN = os.getenv("API_GATEWAY_TOKEN") + +if not VK_GROUP_TOKEN: + raise ValueError("VK_GROUP_TOKEN environment variable is required") + +# Initialize bot +bot = Bot(token=VK_GROUP_TOKEN) + +# State management for conversations +class ConversationState(BaseStateGroup): + WAITING_FOR_MESSAGE = "waiting_for_message" + + +# API Gateway Service +class APIGatewayService: + """Service for interacting with the API Gateway.""" + + def __init__(self, base_url: str, token: str): + self.base_url = base_url + self.token = token + self.session: Optional[aiohttp.ClientSession] = None + + async def init_session(self): + """Initialize HTTP session.""" + if not self.session: + self.session = aiohttp.ClientSession() + + async def close_session(self): + """Close HTTP session.""" + if self.session: + await self.session.close() + + async def chat_completion( + self, + user_id: int, + message: str, + model: str = "gpt-3.5-turbo" + ) -> dict: + """Send chat completion request.""" + await self.init_session() + + try: + async with self.session.post( + f"{self.base_url}/v1/chat/completions", + headers={"Authorization": f"Bearer {self.token}"}, + json={ + "model": model, + "messages": [{"role": "user", "content": message}], + "user_id": str(user_id) + }, + timeout=aiohttp.ClientTimeout(total=60) + ) as response: + if response.status == 200: + return await response.json() + else: + error_text = await response.text() + raise Exception(f"API Gateway error: {response.status} - {error_text}") + except asyncio.TimeoutError: + raise Exception("API Gateway request timeout") + + async def get_user_balance(self, user_id: int) -> int: + """Get user token balance.""" + await self.init_session() + + try: + async with self.session.get( + f"{self.base_url}/tokens/{user_id}", + headers={"Authorization": f"Bearer {self.token}"}, + timeout=aiohttp.ClientTimeout(total=10) + ) as response: + if response.status == 200: + data = await response.json() + return data.get("balance", 0) + else: + # If user doesn't exist, return 0 + return 0 + except Exception as e: + print(f"Error fetching balance: {e}") + return 0 + + +# Initialize API Gateway service +api_gateway = None +if API_GATEWAY_TOKEN: + api_gateway = APIGatewayService(API_GATEWAY_URL, API_GATEWAY_TOKEN) + + +# Keyboard layouts +def get_main_keyboard() -> Keyboard: + """Create main menu keyboard.""" + return ( + Keyboard() + .add(Text("💬 Chat with GPT"), color=KeyboardButtonColor.PRIMARY) + .row() + .add(Text("🎨 Generate Image"), color=KeyboardButtonColor.POSITIVE) + .row() + .add(Text("💰 Balance"), color=KeyboardButtonColor.SECONDARY) + .add(Text("⚙️ Settings"), color=KeyboardButtonColor.SECONDARY) + .row() + .add(Text("ℹ️ Help"), color=KeyboardButtonColor.SECONDARY) + ) + + +def get_cancel_keyboard() -> Keyboard: + """Create keyboard with cancel button.""" + return Keyboard().add(Text("❌ Cancel"), color=KeyboardButtonColor.NEGATIVE) + + +# Command handlers +@bot.on.message(text="/start") +async def start_handler(message: Message): + """Handle /start command.""" + await message.answer( + "👋 Welcome to Deep Assistant VK Bot!\n\n" + "I'm your AI assistant powered by multiple language models. " + "I can help you with:\n\n" + "💬 Chat with AI (GPT-4, Claude, Gemini, etc.)\n" + "🎨 Generate images with DALL-E\n" + "🔊 Transcribe audio messages\n" + "📝 And much more!\n\n" + "Choose an option below to get started:", + keyboard=get_main_keyboard().get_json() + ) + + +@bot.on.message(text=["/help", "ℹ️ Help"]) +async def help_handler(message: Message): + """Handle /help command.""" + await message.answer( + "📚 Help & Commands\n\n" + "Available commands:\n" + "/start - Start the bot\n" + "/help - Show this help message\n" + "/balance - Check your token balance\n" + "/models - List available AI models\n\n" + "Quick Actions:\n" + "💬 Chat with GPT - Start a conversation with AI\n" + "🎨 Generate Image - Create images from text\n" + "💰 Balance - View your token balance\n" + "⚙️ Settings - Configure bot preferences\n\n" + "Need more help? Contact support or visit our documentation.", + keyboard=get_main_keyboard().get_json() + ) + + +@bot.on.message(text=["/balance", "💰 Balance"]) +async def balance_handler(message: Message): + """Handle /balance command.""" + if not api_gateway: + await message.answer( + "⚠️ API Gateway is not configured. Please set up environment variables.", + keyboard=get_main_keyboard().get_json() + ) + return + + try: + balance = await api_gateway.get_user_balance(message.from_id) + await message.answer( + f"💰 Your Balance\n\n" + f"Current balance: {balance} tokens\n\n" + f"Tokens are used for:\n" + f"• AI chat messages (~10-100 tokens per message)\n" + f"• Image generation (~100 tokens per image)\n" + f"• Audio transcription (~50 tokens per minute)\n\n" + f"{'⚠️ Low balance! Consider purchasing more tokens.' if balance < 100 else '✅ You have enough tokens to continue.'}", + keyboard=get_main_keyboard().get_json() + ) + except Exception as e: + await message.answer( + f"❌ Error fetching balance: {str(e)}", + keyboard=get_main_keyboard().get_json() + ) + + +@bot.on.message(text="/models") +async def models_handler(message: Message): + """Handle /models command.""" + await message.answer( + "🤖 Available AI Models\n\n" + "Chat Models:\n" + "• GPT-4 - Most capable OpenAI model\n" + "• GPT-3.5 Turbo - Fast and efficient\n" + "• Claude 3 Opus - Anthropic's best model\n" + "• Claude 3 Sonnet - Balanced performance\n" + "• Gemini Pro - Google's AI model\n" + "• Llama 3 - Meta's open model\n\n" + "Image Models:\n" + "• DALL-E 3 - High-quality image generation\n" + "• Stable Diffusion - Open-source alternative\n\n" + "Use /settings to change your default model.", + keyboard=get_main_keyboard().get_json() + ) + + +@bot.on.message(text=["💬 Chat with GPT"]) +async def chat_start_handler(message: Message): + """Start GPT chat conversation.""" + await bot.state_dispenser.set(message.peer_id, ConversationState.WAITING_FOR_MESSAGE) + + await message.answer( + "💬 Chat Mode Activated\n\n" + "Send me any message and I'll respond using AI. " + "Your conversation history will be maintained.\n\n" + "Type '❌ Cancel' to return to the main menu.", + keyboard=get_cancel_keyboard().get_json() + ) + + +@bot.on.message(text=["❌ Cancel"]) +async def cancel_handler(message: Message): + """Cancel current operation.""" + await bot.state_dispenser.delete(message.peer_id) + + await message.answer( + "Operation cancelled. Returning to main menu.", + keyboard=get_main_keyboard().get_json() + ) + + +@bot.on.message(state=ConversationState.WAITING_FOR_MESSAGE) +async def chat_message_handler(message: Message): + """Handle messages in chat mode.""" + if not api_gateway: + await message.answer( + "⚠️ API Gateway is not configured.", + keyboard=get_main_keyboard().get_json() + ) + await bot.state_dispenser.delete(message.peer_id) + return + + # Check balance + try: + balance = await api_gateway.get_user_balance(message.from_id) + if balance < 10: + await message.answer( + "⚠️ Insufficient balance. You need at least 10 tokens to send a message.\n" + "Use /balance to check your balance.", + keyboard=get_main_keyboard().get_json() + ) + await bot.state_dispenser.delete(message.peer_id) + return + except Exception as e: + print(f"Error checking balance: {e}") + + # Send "typing" indicator + await message.answer("🤔 Thinking...") + + # Send to API Gateway + try: + response = await api_gateway.chat_completion( + user_id=message.from_id, + message=message.text, + model="gpt-3.5-turbo" + ) + + # Extract response text + content = response.get("choices", [{}])[0].get("message", {}).get("content", "") + tokens_used = response.get("usage", {}).get("total_tokens", 0) + + if content: + await message.answer( + f"{content}\n\n" + f"_Tokens used: {tokens_used}_", + keyboard=get_cancel_keyboard().get_json() + ) + else: + await message.answer( + "❌ Received empty response from API.", + keyboard=get_cancel_keyboard().get_json() + ) + + except Exception as e: + await message.answer( + f"❌ Error: {str(e)}\n\n" + "Please try again or contact support if the issue persists.", + keyboard=get_main_keyboard().get_json() + ) + await bot.state_dispenser.delete(message.peer_id) + + +@bot.on.message(text=["🎨 Generate Image"]) +async def image_handler(message: Message): + """Handle image generation request.""" + await message.answer( + "🎨 Image Generation\n\n" + "This feature will be available soon!\n\n" + "You'll be able to generate images by describing what you want to see.", + keyboard=get_main_keyboard().get_json() + ) + + +@bot.on.message(text=["⚙️ Settings"]) +async def settings_handler(message: Message): + """Handle settings request.""" + await message.answer( + "⚙️ Settings\n\n" + "Settings panel will be available soon!\n\n" + "You'll be able to:\n" + "• Choose your preferred AI model\n" + "• Set language preference\n" + "• Configure conversation history\n" + "• And more!", + keyboard=get_main_keyboard().get_json() + ) + + +@bot.on.message() +async def fallback_handler(message: Message): + """Handle unknown messages.""" + await message.answer( + "🤔 I didn't understand that command.\n\n" + "Use the buttons below or type /help to see available commands.", + keyboard=get_main_keyboard().get_json() + ) + + +# Main entry point +async def main(): + """Main function to run the bot.""" + print("🤖 VK Bot is starting...") + print(f"📡 API Gateway URL: {API_GATEWAY_URL}") + print(f"🔐 API Gateway configured: {'Yes' if API_GATEWAY_TOKEN else 'No'}") + print("✅ Bot is ready!") + + try: + await bot.run_polling() + finally: + if api_gateway: + await api_gateway.close_session() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/python-bot/requirements.txt b/examples/python-bot/requirements.txt new file mode 100644 index 0000000..22ec3bb --- /dev/null +++ b/examples/python-bot/requirements.txt @@ -0,0 +1,3 @@ +vkbottle>=4.3.0 +aiohttp>=3.8.0 +python-dotenv>=1.0.0