Initial commit: VoIdeaAI - voice-first AI idea assistant

This commit is contained in:
2026-05-13 12:51:42 +03:00
commit 688d043dad
421 changed files with 47915 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
"""VoIdea - Integrations module (AI providers, external services)."""
+14
View File
@@ -0,0 +1,14 @@
"""VoIdea - AI integration module."""
from app.integrations.ai.base import AIProvider, AIResult
from app.integrations.ai.yandex_gpt import YandexGPTProvider
from app.integrations.ai.gigachat import GigaChatProvider
from app.integrations.ai.fallback import FallbackChain
__all__ = [
"AIProvider",
"AIResult",
"YandexGPTProvider",
"GigaChatProvider",
"FallbackChain",
]
+64
View File
@@ -0,0 +1,64 @@
"""Base classes for AI provider integration."""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any
@dataclass
class AIResult:
"""Result from an AI provider call."""
success: bool
content: str = ""
model: str = ""
provider: str = ""
tokens_used: int = 0
duration_ms: int = 0
error: str = ""
metadata: dict[str, Any] = field(default_factory=dict)
class AIProvider(ABC):
"""Abstract base class for AI providers.
All AI providers (Yandex GPT, GigaChat, etc.) must implement this.
"""
name: str = ""
model: str = ""
timeout: int = 10
max_retries: int = 3
def __init__(self, api_key: str = "", **kwargs: Any):
self.api_key = api_key
for key, value in kwargs.items():
setattr(self, key, value)
self._initialize()
def _initialize(self) -> None:
"""Post-initialization hook for provider-specific setup."""
@abstractmethod
async def analyze(self, prompt: str, **kwargs: Any) -> AIResult:
"""Send a prompt to the AI provider and return the result.
Args:
prompt: The formatted prompt to send
**kwargs: Additional provider-specific parameters
Returns:
AIResult with the response content
"""
def format_prompt(
self, system_prompt: str, user_prompt: str, **kwargs: Any
) -> str:
"""Format a prompt with system instructions and user message.
Override in provider if the API uses separate system/user messages.
"""
return f"{system_prompt}\n\n{user_prompt}"
+99
View File
@@ -0,0 +1,99 @@
"""Fallback chain for AI providers.
Tries providers in order with retries per provider.
YandexGPT -> GigaChat -> Error
"""
import asyncio
import time
from typing import Any
from app.core.config import get_settings
from app.integrations.ai.base import AIProvider, AIResult
from app.integrations.ai.yandex_gpt import YandexGPTProvider
from app.integrations.ai.gigachat import GigaChatProvider
settings = get_settings()
class FallbackChain:
"""Chain multiple AI providers with retry logic.
Tries providers in order (YandexGPT -> GigaChat).
Each provider gets up to `max_retries` attempts before falling through.
"""
def __init__(
self,
providers: list[AIProvider] | None = None,
max_retries: int = 2,
timeout: int = 30,
):
self.providers = providers or [
YandexGPTProvider(),
GigaChatProvider(),
]
self.max_retries = max_retries
self.timeout = timeout
async def analyze(self, prompt: str, **kwargs: Any) -> AIResult:
"""Try each provider in order with retries.
Args:
prompt: The formatted prompt to send
**kwargs: Additional parameters passed to each provider
Returns:
AIResult from the first successful provider,
or the last error result if all fail.
"""
last_error: AIResult | None = None
for provider in self.providers:
for attempt in range(self.max_retries + 1):
try:
result = await asyncio.wait_for(
provider.analyze(prompt, **kwargs),
timeout=self.timeout,
)
if result.success:
await self._cleanup_providers(provider)
return result
last_error = result
except asyncio.TimeoutError:
last_error = AIResult(
success=False,
error=f"{provider.name} timeout after {self.timeout}s",
provider=provider.name,
duration_ms=int(self.timeout * 1000),
)
except Exception as e:
last_error = AIResult(
success=False,
error=f"{provider.name} error: {str(e)}",
provider=provider.name,
)
if attempt < self.max_retries:
await asyncio.sleep(1 * (attempt + 1))
await self._cleanup_providers()
return last_error or AIResult(
success=False,
error="All providers failed",
provider="fallback_chain",
)
async def _cleanup_providers(self, skip: AIProvider | None = None) -> None:
"""Close all provider clients except the one to keep."""
for provider in self.providers:
if provider is skip:
continue
if hasattr(provider, "close"):
try:
await provider.close()
except Exception:
pass
+160
View File
@@ -0,0 +1,160 @@
"""GigaChat provider for VoIdea."""
import base64
import time
from datetime import datetime, timezone
from typing import Any, Optional
import httpx
from app.core.config import get_settings
from app.integrations.ai.base import AIProvider, AIResult
settings = get_settings()
class GigaChatProvider(AIProvider):
"""GigaChat AI provider (Sber).
Uses OAuth client credentials for authentication.
Token is refreshed automatically on 401.
"""
name = "gigachat"
model = "GigaChat"
timeout = settings.ai_timeout
max_retries = settings.ai_max_retries
def __init__(self, api_key: str = ""):
super().__init__(api_key)
self.base_url = settings.ai_gigachat_url.rstrip("/")
self.client_id = settings.ai_gigachat_client_id
self.client_secret = settings.ai_gigachat_secret
self._client = httpx.AsyncClient(timeout=self.timeout)
self._access_token: Optional[str] = None
self._token_expires_at: float = 0
async def _get_access_token(self) -> Optional[str]:
"""Get or refresh GigaChat access token."""
if self._access_token and time.time() < self._token_expires_at:
return self._access_token
if not self.client_id or not self.client_secret:
return None
auth_str = base64.b64encode(
f"{self.client_id}:{self.client_secret}".encode()
).decode()
try:
response = await self._client.post(
"https://ngw.devices.sber.ru/token",
headers={
"Authorization": f"Basic {auth_str}",
"Content-Type": "application/x-www-form-urlencoded",
"RqUID": str(time.time()),
},
data={"scope": "GIGACHAT_API_PERS"},
)
if response.status_code == 200:
data = response.json()
self._access_token = data.get("access_token")
expires_in = data.get("expires_in", 1800)
self._token_expires_at = time.time() + expires_in - 60
return self._access_token
except Exception:
return None
return None
async def analyze(self, prompt: str, **kwargs: Any) -> AIResult:
"""Send prompt to GigaChat and return result."""
start = time.time()
temperature = kwargs.get("temperature", 0.7)
max_tokens = kwargs.get("max_tokens", 2000)
token = await self._get_access_token()
if not token:
return AIResult(
success=False,
error="GigaChat authentication failed",
provider=self.name,
)
parts = prompt.split("\n\n", 1)
system_text = parts[0]
user_text = parts[1] if len(parts) > 1 else ""
body = {
"model": self.model,
"temperature": temperature,
"max_tokens": max_tokens,
"messages": [
{"role": "system", "content": system_text},
{"role": "user", "content": user_text},
],
}
try:
response = await self._client.post(
f"{self.base_url}/api/v1/chat/completion",
json=body,
headers={"Authorization": f"Bearer {token}"},
)
duration = int((time.time() - start) * 1000)
if response.status_code == 401:
self._access_token = None
token = await self._get_access_token()
if token:
response = await self._client.post(
f"{self.base_url}/api/v1/chat/completion",
json=body,
headers={"Authorization": f"Bearer {token}"},
)
duration = int((time.time() - start) * 1000)
if response.status_code == 200:
data = response.json()
result_text = (
data.get("choices", [{}])[0]
.get("message", {})
.get("content", "")
)
return AIResult(
success=True,
content=result_text,
model=self.model,
provider=self.name,
duration_ms=duration,
)
else:
error_body = response.text[:500]
return AIResult(
success=False,
error=f"GigaChat {response.status_code}: {error_body}",
provider=self.name,
duration_ms=duration,
)
except httpx.TimeoutException:
return AIResult(
success=False,
error="GigaChat timeout",
provider=self.name,
duration_ms=int((time.time() - start) * 1000),
)
except Exception as e:
return AIResult(
success=False,
error=f"GigaChat error: {str(e)}",
provider=self.name,
duration_ms=int((time.time() - start) * 1000),
)
async def close(self) -> None:
await self._client.aclose()
+90
View File
@@ -0,0 +1,90 @@
"""Prompt loader for AI agents.
Loads prompts from agent spec files or YAML configuration.
"""
import re
from pathlib import Path
from typing import Any, Optional
import yaml
AGENT_SPECS_DIR = Path("docs/specs/agents")
AGENT_PROMPTS_YAML = Path("docs/agent_prompts.yaml")
def get_agent_roles() -> list[str]:
"""Get all available agent roles."""
roles = []
if AGENT_PROMPTS_YAML.exists():
data = yaml.safe_load(AGENT_PROMPTS_YAML.read_text(encoding="utf-8"))
return list(data.keys()) if data else []
if AGENT_SPECS_DIR.exists():
for f in sorted(AGENT_SPECS_DIR.glob("*.md")):
roles.append(f.stem)
return roles
def load_prompt_from_yaml(role: str) -> Optional[dict[str, Any]]:
"""Load prompt config from YAML file."""
if not AGENT_PROMPTS_YAML.exists():
return None
data = yaml.safe_load(AGENT_PROMPTS_YAML.read_text(encoding="utf-8"))
return data.get(role) if data else None
def load_prompt_from_spec(role: str) -> Optional[dict[str, Any]]:
"""Load prompt from agent spec markdown file."""
spec_path = AGENT_SPECS_DIR / f"{role}.md"
if not spec_path.exists():
return None
content = spec_path.read_text(encoding="utf-8")
def extract_field(label: str) -> Optional[str]:
match = re.search(rf"\*\*{label}:\*\*\s*(.+)", content)
return match.group(1).strip() if match else None
def extract_prompt() -> Optional[str]:
match = re.search(
r"## Prompt Template\n+```\n(.+?)\n```",
content,
re.DOTALL,
)
return match.group(1).strip() if match else None
provider_str = extract_field("Провайдер") or extract_field("Provider") or "yandex_gpt"
provider = "gigachat" if "gigachat" in (provider_str or "").lower() else "yandex_gpt"
prompt_text = extract_prompt()
if not prompt_text:
return None
return {
"system_prompt": prompt_text,
"provider": provider,
"temperature": 0.7,
"max_tokens": 2000,
}
def get_prompt_config(role: str) -> Optional[dict[str, Any]]:
"""Get prompt configuration for a role.
Tries YAML first, falls back to spec markdown.
Args:
role: Agent role name (e.g. "coordinator", "business_analyst")
Returns:
Dict with keys: system_prompt, provider, temperature, max_tokens
or None if not found.
"""
config = load_prompt_from_yaml(role)
if config:
return config
return load_prompt_from_spec(role)
+122
View File
@@ -0,0 +1,122 @@
"""Yandex GPT provider for VoIdea."""
import time
from datetime import datetime, timezone
from typing import Any, Optional
import httpx
from app.core.config import get_settings
from app.integrations.ai.base import AIProvider, AIResult
settings = get_settings()
class YandexGPTProvider(AIProvider):
"""Yandex GPT AI provider.
Supports both API key (Api-Key header) and IAM token (Bearer header).
Automatically falls back between auth methods on 401.
"""
name = "yandex_gpt"
model = "yandexgpt/latest"
timeout = settings.ai_timeout
max_retries = settings.ai_max_retries
def __init__(self, api_key: str = ""):
super().__init__(api_key or settings.ai_yandex_key)
self.base_url = settings.ai_yandex_url.rstrip("/")
self.folder_id = settings.ai_yandex_folder_id
self._client = httpx.AsyncClient(timeout=self.timeout)
async def analyze(self, prompt: str, **kwargs: Any) -> AIResult:
"""Send prompt to Yandex GPT and return result."""
start = time.time()
temperature = kwargs.get("temperature", 0.7)
max_tokens = kwargs.get("max_tokens", 2000)
model_uri = f"gpt://{self.folder_id}/{self.model}" if self.folder_id else self.model
# Split prompt into system and user parts
parts = prompt.split("\n\n", 1)
system_text = parts[0]
user_text = parts[1] if len(parts) > 1 else ""
body = {
"modelUri": model_uri,
"completionOptions": {
"temperature": temperature,
"maxTokens": max_tokens,
},
"messages": [
{"role": "system", "text": system_text},
{"role": "user", "text": user_text},
],
}
try:
response = await self._client.post(
f"{self.base_url}/foundationModels/v1/completion",
json=body,
)
duration = int((time.time() - start) * 1000)
if response.status_code == 401:
# Try with Api-Key header instead
response = await self._client.post(
f"{self.base_url}/foundationModels/v1/completion",
json=body,
headers={"Authorization": f"Api-Key {self.api_key}"},
)
duration = int((time.time() - start) * 1000)
if response.status_code == 200:
data = response.json()
result_text = (
data.get("result", {})
.get("alternatives", [{}])[0]
.get("message", {})
.get("text", "")
)
tokens = (
data.get("result", {})
.get("usage", {})
.get("inputTextTokens", 0)
)
return AIResult(
success=True,
content=result_text,
model=self.model,
provider=self.name,
tokens_used=tokens,
duration_ms=duration,
)
else:
error_body = response.text[:500]
return AIResult(
success=False,
error=f"Yandex GPT {response.status_code}: {error_body}",
provider=self.name,
duration_ms=duration,
)
except httpx.TimeoutException:
return AIResult(
success=False,
error="Yandex GPT timeout",
provider=self.name,
duration_ms=int((time.time() - start) * 1000),
)
except Exception as e:
return AIResult(
success=False,
error=f"Yandex GPT error: {str(e)}",
provider=self.name,
duration_ms=int((time.time() - start) * 1000),
)
async def close(self) -> None:
await self._client.aclose()
+55
View File
@@ -0,0 +1,55 @@
"""OAuth integrations for VoIdeaAI."""
from app.integrations.oauth.yandex import (
get_authorize_url as yandex_authorize_url,
exchange_code as yandex_exchange_code,
get_user_info as yandex_user_info,
ensure_app_folder as yandex_ensure_folder,
upload_file as yandex_upload_file,
get_disk_info as yandex_disk_info,
YandexUserInfo,
YandexTokenResult,
VOIDEA_DISK_FOLDER,
)
from app.integrations.oauth.google import (
is_available as google_is_available,
get_authorize_url as google_authorize_url,
exchange_code as google_exchange_code,
get_user_info as google_user_info,
ensure_app_folder as google_ensure_folder,
upload_file as google_upload_file,
get_disk_info as google_disk_info,
GoogleUserInfo,
)
from app.integrations.oauth.apple import (
is_available as apple_is_available,
get_authorize_url as apple_authorize_url,
exchange_code as apple_exchange_code,
get_user_info as apple_user_info,
AppleUserInfo,
)
__all__ = [
"yandex_authorize_url",
"yandex_exchange_code",
"yandex_user_info",
"yandex_ensure_folder",
"yandex_upload_file",
"yandex_disk_info",
"YandexUserInfo",
"YandexTokenResult",
"VOIDEA_DISK_FOLDER",
"google_is_available",
"google_authorize_url",
"google_exchange_code",
"google_user_info",
"google_ensure_folder",
"google_upload_file",
"google_disk_info",
"GoogleUserInfo",
"apple_is_available",
"apple_authorize_url",
"apple_exchange_code",
"apple_user_info",
"AppleUserInfo",
]
+92
View File
@@ -0,0 +1,92 @@
"""Apple OAuth client with iCloud Drive API support.
Activated when OAUTH_APPLE_ID is set in .env.
Note: Apple requires Sign in with Apple capability and team ID configuration.
"""
from dataclasses import dataclass
import httpx
from app.core.config import get_settings
APPLE_OAUTH_URL = "https://appleid.apple.com/auth/authorize"
APPLE_TOKEN_URL = "https://appleid.apple.com/auth/token"
SCOPES = "name email"
VOIDEA_DRIVE_FOLDER = "VoIdeaAI"
@dataclass
class AppleUserInfo:
id: str
email: str
display_name: str
def is_available() -> bool:
return get_settings().apple_oauth_enabled
async def get_authorize_url() -> str:
settings = get_settings()
params = {
"response_type": "code id_token",
"client_id": settings.oauth_apple_id,
"redirect_uri": settings.oauth_apple_redirect_uri,
"scope": SCOPES,
"response_mode": "form_post",
}
query = "&".join(f"{k}={v}" for k, v in params.items())
return f"{APPLE_OAUTH_URL}?{query}"
async def exchange_code(code: str) -> dict | None:
settings = get_settings()
if not settings.apple_oauth_enabled:
return None
async with httpx.AsyncClient() as client:
resp = await client.post(
APPLE_TOKEN_URL,
data={
"grant_type": "authorization_code",
"code": code,
"client_id": settings.oauth_apple_id,
"client_secret": settings.oauth_apple_secret,
"redirect_uri": settings.oauth_apple_redirect_uri,
},
)
if resp.status_code != 200:
return None
return resp.json()
async def get_user_info(access_token: str) -> AppleUserInfo | None:
"""Apple returns user info only in the initial authorization response,
not from a userinfo endpoint. This method decodes the id_token claims.
"""
async with httpx.AsyncClient() as client:
resp = await client.get(
"https://appleid.apple.com/auth/keys",
)
if resp.status_code != 200:
return None
return None # Full implementation requires JWT id_token decoding
async def ensure_app_folder(access_token: str) -> str | None:
return None # iCloud Drive API requires additional entitlements
async def upload_file(
access_token: str,
file_name: str,
file_content: bytes,
parent_id: str | None = None,
) -> bool:
return False # Requires CloudKit API integration
async def get_disk_info(access_token: str) -> dict | None:
return None # Requires CloudKit API integration
+135
View File
@@ -0,0 +1,135 @@
"""Google OAuth client with Google Drive API support.
Activated when OAUTH_GOOGLE_ID is set in .env.
"""
from dataclasses import dataclass
import httpx
from app.core.config import get_settings
GOOGLE_OAUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"
GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token"
GOOGLE_USERINFO_URL = "https://www.googleapis.com/oauth2/v2/userinfo"
GOOGLE_DRIVE_URL = "https://www.googleapis.com/drive/v3"
SCOPES = " ".join([
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/drive.file",
])
VOIDEA_DRIVE_FOLDER = "VoIdeaAI"
@dataclass
class GoogleUserInfo:
id: str
email: str
display_name: str
avatar_url: str | None
def is_available() -> bool:
return get_settings().google_oauth_enabled
async def get_authorize_url() -> str:
settings = get_settings()
params = {
"response_type": "code",
"client_id": settings.oauth_google_id,
"redirect_uri": settings.oauth_google_redirect_uri,
"scope": SCOPES,
"access_type": "offline",
"prompt": "consent",
}
query = "&".join(f"{k}={v}" for k, v in params.items())
return f"{GOOGLE_OAUTH_URL}?{query}"
async def exchange_code(code: str) -> dict | None:
settings = get_settings()
if not settings.google_oauth_enabled:
return None
async with httpx.AsyncClient() as client:
resp = await client.post(
GOOGLE_TOKEN_URL,
data={
"grant_type": "authorization_code",
"code": code,
"client_id": settings.oauth_google_id,
"client_secret": settings.oauth_google_secret,
"redirect_uri": settings.oauth_google_redirect_uri,
},
)
if resp.status_code != 200:
return None
return resp.json()
async def get_user_info(access_token: str) -> GoogleUserInfo | None:
async with httpx.AsyncClient() as client:
resp = await client.get(
GOOGLE_USERINFO_URL,
headers={"Authorization": f"Bearer {access_token}"},
)
if resp.status_code != 200:
return None
data = resp.json()
return GoogleUserInfo(
id=data["id"],
email=data["email"],
display_name=data.get("name", data["email"]),
avatar_url=data.get("picture"),
)
async def ensure_app_folder(access_token: str) -> str | None:
async with httpx.AsyncClient() as client:
resp = await client.post(
f"{GOOGLE_DRIVE_URL}/files",
headers={
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
},
json={
"name": VOIDEA_DRIVE_FOLDER,
"mimeType": "application/vnd.google-apps.folder",
},
)
if resp.status_code == 200:
return resp.json().get("id")
return None
async def upload_file(
access_token: str,
file_name: str,
file_content: bytes,
parent_id: str | None = None,
) -> bool:
metadata = {"name": file_name}
if parent_id:
metadata["parents"] = [parent_id]
async with httpx.AsyncClient() as client:
resp = await client.post(
f"{GOOGLE_DRIVE_URL}/files?uploadType=multipart",
headers={"Authorization": f"Bearer {access_token}"},
data={"metadata": str(metadata)},
files={"file": (file_name, file_content)},
)
return resp.status_code == 200
async def get_disk_info(access_token: str) -> dict | None:
async with httpx.AsyncClient() as client:
resp = await client.get(
f"{GOOGLE_DRIVE_URL}/about?fields=storageQuota",
headers={"Authorization": f"Bearer {access_token}"},
)
if resp.status_code != 200:
return None
return resp.json()
+204
View File
@@ -0,0 +1,204 @@
"""Yandex OAuth client with Disk API support.
Scopes requested:
- login:email — email address
- login:info — login, first+last name
- login:avatar — avatar URL
- cloud_api:disk.write — write anywhere on Disk
- cloud_api:disk.app_folder — access app folder on Disk
- cloud_api:disk.read — read entire Disk
- cloud_api:disk.info — Disk info (quota, etc.)
"""
from dataclasses import dataclass
import httpx
from app.core.config import get_settings
YANDEX_OAUTH_URL = "https://oauth.yandex.ru"
YANDEX_LOGIN_URL = "https://login.yandex.ru"
YANDEX_DISK_URL = "https://cloud-api.yandex.net/v1/disk"
SCOPES = " ".join([
"login:email",
"login:info",
"login:avatar",
"cloud_api:disk.write",
"cloud_api:disk.app_folder",
"cloud_api:disk.read",
"cloud_api:disk.info",
])
VOIDEA_DISK_FOLDER = "VoIdeaAI"
@dataclass
class YandexUserInfo:
id: str
login: str
email: str
display_name: str
avatar_url: str | None
@dataclass
class YandexTokenResult:
access_token: str
refresh_token: str | None
expires_in: int
async def get_authorize_url() -> str:
"""Generate Yandex OAuth authorization URL."""
settings = get_settings()
params = {
"response_type": "code",
"client_id": settings.oauth_yandex_id,
"redirect_uri": settings.oauth_yandex_redirect_uri,
"scope": SCOPES,
}
query = "&".join(f"{k}={v}" for k, v in params.items())
return f"{YANDEX_OAUTH_URL}/authorize?{query}"
async def exchange_code(code: str) -> YandexTokenResult | None:
"""Exchange authorization code for access token.
Args:
code: Authorization code from OAuth callback
Returns:
Token result or None if exchange failed
"""
settings = get_settings()
if not settings.oauth_yandex_id or not settings.oauth_yandex_secret:
return None
async with httpx.AsyncClient() as client:
resp = await client.post(
f"{YANDEX_OAUTH_URL}/token",
data={
"grant_type": "authorization_code",
"code": code,
"client_id": settings.oauth_yandex_id,
"client_secret": settings.oauth_yandex_secret,
},
)
if resp.status_code != 200:
return None
data = resp.json()
return YandexTokenResult(
access_token=data["access_token"],
refresh_token=data.get("refresh_token"),
expires_in=data.get("expires_in", 0),
)
async def get_user_info(access_token: str) -> YandexUserInfo | None:
"""Get user info from Yandex Login API.
Args:
access_token: Valid OAuth access token
Returns:
User info or None if request failed
"""
async with httpx.AsyncClient() as client:
resp = await client.get(
f"{YANDEX_LOGIN_URL}/info",
params={"format": "json"},
headers={"Authorization": f"OAuth {access_token}"},
)
if resp.status_code != 200:
return None
data = resp.json()
avatar_url: str | None = None
if data.get("default_avatar_id"):
avatar_url = (
f"https://avatars.yandex.net/get-yapic/{data['default_avatar_id']}/islands-200"
)
display_name = data.get("real_name") or data.get("display_name") or data.get("login", "")
email = data.get("default_email") or ""
return YandexUserInfo(
id=str(data["id"]),
login=data.get("login", ""),
email=email,
display_name=display_name,
avatar_url=avatar_url,
)
async def ensure_app_folder(access_token: str) -> bool:
"""Create VoIdeaAI folder on Yandex.Disk if it doesn't exist.
Args:
access_token: Valid OAuth access token with disk.write scope
Returns:
True if folder exists (created or already present)
"""
async with httpx.AsyncClient() as client:
resp = await client.put(
f"{YANDEX_DISK_URL}/resources",
params={"path": VOIDEA_DISK_FOLDER},
headers={"Authorization": f"OAuth {access_token}"},
)
return resp.status_code in (201, 409)
async def get_disk_info(access_token: str) -> dict | None:
"""Get Yandex.Disk info (quota, usage).
Args:
access_token: Valid OAuth access token
Returns:
Disk info dict or None
"""
async with httpx.AsyncClient() as client:
resp = await client.get(
f"{YANDEX_DISK_URL}",
headers={"Authorization": f"OAuth {access_token}"},
)
return resp.json() if resp.status_code == 200 else None
async def upload_file(access_token: str, local_path: str, remote_name: str) -> bool:
"""Upload a file to VoIdeaAI folder on Yandex.Disk.
Args:
access_token: Valid OAuth access token
local_path: Path to local file
remote_name: Name for the file on Disk
Returns:
True if upload succeeded
"""
import os
if not os.path.exists(local_path):
return False
remote_path = f"{VOIDEA_DISK_FOLDER}/{remote_name}"
async with httpx.AsyncClient() as client:
# 1. Get upload URL
resp = await client.get(
f"{YANDEX_DISK_URL}/resources/upload",
params={"path": remote_path, "overwrite": "true"},
headers={"Authorization": f"OAuth {access_token}"},
)
if resp.status_code != 200:
return False
upload_url = resp.json().get("href")
if not upload_url:
return False
# 2. Upload file
with open(local_path, "rb") as f:
upload_resp = await client.put(upload_url, content=f)
return upload_resp.status_code in (201, 202)
+1
View File
@@ -0,0 +1 @@
"""Telegram bot integration for VoIdea."""
+27
View File
@@ -0,0 +1,27 @@
"""Telegram ↔ VoIdea account linking."""
from __future__ import annotations
import secrets
from typing import Any
# In-memory store for link tokens (in production: Redis with TTL)
_link_tokens: dict[str, int] = {} # token → user_id
def create_link_token(user_id: int) -> str:
"""Generate a one-time token for linking Telegram to VoIdea account."""
token = secrets.token_urlsafe(32)
_link_tokens[token] = user_id
return token
def consume_link_token(token: str) -> int | None:
"""Validate and consume a link token. Returns user_id or None."""
user_id = _link_tokens.pop(token, None)
return user_id
def get_bot_link_url(base_url: str, token: str) -> str:
"""Return the URL for the user to confirm account linking."""
return f"{base_url}/bot/link?token={token}"
+77
View File
@@ -0,0 +1,77 @@
"""Telegram bot client — stub implementation.
Replace with python-telegram-bot or aiogram when TELEGRAM_BOT_TOKEN is set.
"""
from __future__ import annotations
import logging
from typing import Any
logger = logging.getLogger("voidea.telegram.bot")
class TelegramBotClient:
"""Stub Telegram bot client.
All methods log instead of calling Telegram API.
Replace with real implementation when TELEGRAM_BOT_TOKEN is configured.
"""
def __init__(self, token: str | None = None):
self.token = token
self.available = bool(token)
if self.available:
logger.info("Telegram bot client initialized with token")
else:
logger.warning("TELEGRAM_BOT_TOKEN not set — bot is in stub mode")
async def send_message(
self,
chat_id: int | str,
text: str,
parse_mode: str = "HTML",
reply_markup: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
"""Send a message to a Telegram chat."""
if not self.available:
logger.info("[STUB] send_message to %s: %s", chat_id, text[:80])
return None
# TODO: real Telegram API call
logger.info("send_message to %s: %s", chat_id, text[:80])
return {"ok": True}
async def send_voice(
self,
chat_id: int | str,
voice_url: str,
) -> dict[str, Any] | None:
"""Send a voice message."""
if not self.available:
logger.info("[STUB] send_voice to %s: %s", chat_id, voice_url[:80])
return None
logger.info("send_voice to %s: %s", chat_id, voice_url[:80])
return {"ok": True}
async def set_webhook(self, url: str) -> bool:
"""Set the Telegram bot webhook URL."""
if not self.available:
logger.info("[STUB] set_webhook: %s", url)
return False
logger.info("set_webhook: %s", url)
return True
async def delete_webhook(self) -> bool:
"""Remove the webhook."""
if not self.available:
logger.info("[STUB] delete_webhook")
return False
return True
async def set_commands(self, commands: list[dict[str, str]]) -> bool:
"""Register bot commands with Telegram."""
if not self.available:
logger.info("[STUB] set_commands: %s", [c["command"] for c in commands])
return False
logger.info("set_commands: %d commands", len(commands))
return True
+52
View File
@@ -0,0 +1,52 @@
"""Command decorator for auto-registration of bot commands.
Usage:
@bot_command(name="/idea", description="Create a new idea", requires_auth=True)
async def cmd_idea(update, context): ...
"""
from __future__ import annotations
import inspect
from dataclasses import dataclass, field
from typing import Any, Callable
@dataclass
class BotCommandDef:
name: str
description: str
requires_auth: bool = False
handler: Callable | None = None
_registry: list[BotCommandDef] = []
def bot_command(
name: str,
description: str,
requires_auth: bool = False,
) -> Callable:
"""Decorator that registers a function as a bot command handler."""
def wrapper(func: Callable) -> Callable:
_registry.append(BotCommandDef(
name=name,
description=description,
requires_auth=requires_auth,
handler=func,
))
return func
return wrapper
def get_registered_commands() -> list[BotCommandDef]:
"""Return all registered command definitions."""
return list(_registry)
def get_enabled_commands(enabled_names: set[str]) -> list[BotCommandDef]:
"""Return only commands that are in the enabled set."""
return [cmd for cmd in _registry if cmd.name in enabled_names]
+84
View File
@@ -0,0 +1,84 @@
"""Telegram bot command handlers.
Registered via @bot_command decorator for auto-discovery.
"""
from __future__ import annotations
import logging
from typing import Any
from app.integrations.telegram.auth import create_link_token, get_bot_link_url
from app.integrations.telegram.decorators import bot_command
from app.integrations.telegram.client import TelegramBotClient
logger = logging.getLogger("voidea.telegram.handlers")
_bot_client: TelegramBotClient | None = None
def set_bot_client(client: TelegramBotClient) -> None:
global _bot_client
_bot_client = client
@bot_command(name="/start", description="Welcome message and getting started")
async def cmd_start(update: dict[str, Any], context: dict[str, Any]) -> str:
user = update.get("message", {}).get("from", {})
first_name = user.get("first_name", "User")
return (
f"Hello, {first_name}! 👋\n\n"
"I'm VoIdeaAI bot. Here's what I can do:\n"
"/link — Link your Telegram to VoIdea account\n"
"/idea — Create a new idea (requires linking)\n"
"/help — Show available commands"
)
@bot_command(name="/help", description="Show available commands")
async def cmd_help(update: dict[str, Any], context: dict[str, Any]) -> str:
return (
"Available commands:\n"
"/start — Welcome message\n"
"/link — Link Telegram to your VoIdea account\n"
"/idea — Create a new idea from text\n"
"/help — This message\n\n"
"To get started, use /link to connect your account."
)
@bot_command(name="/link", description="Link Telegram to your VoIdea account")
async def cmd_link(update: dict[str, Any], context: dict[str, Any]) -> str:
user_id = update.get("message", {}).get("from", {}).get("id")
if not user_id:
return "Error: could not identify you."
token = create_link_token(int(user_id))
base_url = context.get("base_url", "https://voidea.ai")
link_url = get_bot_link_url(base_url, token)
return (
"To link your Telegram account to VoIdea:\n\n"
f"1. Open this link: {link_url}\n"
"2. Confirm the pairing\n"
"3. Come back and use /idea to create ideas\n\n"
"The link expires in 30 minutes."
)
@bot_command(name="/idea", description="Create a new idea (requires linking)")
async def cmd_idea(update: dict[str, Any], context: dict[str, Any]) -> str:
text = update.get("message", {}).get("text", "")
args = text.replace("/idea", "", 1).strip()
if not args:
return (
"Usage: /idea <your idea text>\n\n"
"Example: /idea A mobile app for tracking daily water intake\n\n"
"You need to link your account first with /link."
)
return (
f"Idea received: \"{args[:200]}\"\n\n"
"To save it permanently, link your account with /link first.\n"
"After linking, your ideas will appear in your VoIdea dashboard."
)
+91
View File
@@ -0,0 +1,91 @@
"""Telegram bot command sync service.
Synchronises @bot_command-decorated handlers with BotCommand DB table
and Telegram Bot API (set_my_commands) on boot or manual trigger.
"""
from __future__ import annotations
import logging
from typing import Any
from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import AsyncSession
from app.integrations.telegram.client import TelegramBotClient
from app.integrations.telegram.decorators import get_registered_commands
from app.models.bot_command import BotCommand
logger = logging.getLogger("voidea.telegram.sync")
class TelegramBotSyncService:
"""Syncs registered bot commands to DB and Telegram API."""
def __init__(self, db: AsyncSession, bot_client: TelegramBotClient | None = None):
self.db = db
self.bot_client = bot_client
async def sync_to_db(self) -> list[BotCommand]:
"""Ensure all @bot_command handlers have matching BotCommand records."""
registered = get_registered_commands()
result = await self.db.execute(select(BotCommand))
existing = {cmd.name: cmd for cmd in result.scalars().all()}
synced: list[BotCommand] = []
for reg in registered:
if reg.name in existing:
cmd = existing[reg.name]
if cmd.description != reg.description or cmd.requires_auth != reg.requires_auth:
cmd.description = reg.description
cmd.requires_auth = reg.requires_auth
synced.append(cmd)
else:
cmd = BotCommand(
name=reg.name,
description=reg.description,
enabled=True,
requires_auth=reg.requires_auth,
)
self.db.add(cmd)
synced.append(cmd)
await self.db.commit()
for cmd in synced:
await self.db.refresh(cmd)
logger.info("Synced %d bot commands to DB", len(synced))
return synced
async def sync_to_telegram(self) -> bool:
"""Push enabled commands to Telegram Bot API via set_my_commands."""
if not self.bot_client or not self.bot_client.available:
logger.info("Telegram client not available — skipping set_my_commands")
return False
result = await self.db.execute(
select(BotCommand).where(BotCommand.enabled == True)
)
enabled = result.scalars().all()
commands = [
{"command": cmd.name.lstrip("/"), "description": cmd.description}
for cmd in enabled
]
ok = await self.bot_client.set_commands(commands)
if ok:
logger.info("Pushed %d commands to Telegram", len(commands))
else:
logger.warning("Failed to push commands to Telegram")
return ok
async def full_sync(self) -> dict[str, Any]:
"""Run full sync: DB → Telegram."""
synced = await self.sync_to_db()
telegram_ok = await self.sync_to_telegram()
return {
"synced_count": len(synced),
"telegram_sync": telegram_ok,
}