smart-bot-factory 0.1.8__tar.gz → 0.1.9__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of smart-bot-factory might be problematic. Click here for more details.
- smart_bot_factory-0.1.9/PKG-INFO +602 -0
- smart_bot_factory-0.1.9/README.md +569 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/pyproject.toml +1 -1
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/core/decorators.py +1 -1
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/integrations/supabase_client.py +8 -18
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/uv.lock +1 -1
- smart_bot_factory-0.1.8/PKG-INFO +0 -126
- smart_bot_factory-0.1.8/README.md +0 -93
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/.github/ISSUE_TEMPLATE//342/234/250-/320/267/320/260/320/277/321/200/320/276/321/201-/321/204/321/203/320/275/320/272/321/206/320/270/320/270.md" +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/.github/ISSUE_TEMPLATE//360/237/220/233-/320/261/320/260/320/263-/321/200/320/265/320/277/320/276/321/200/321/202.md" +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/.github/workflows/ci.yml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/.github/workflows/publish-private.yml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/.github/workflows/publish.yml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/.gitignore +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/.python-version +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/CLIENTS_USAGE.md +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/Dockerfile +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/LICENSE +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/best-valera.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/best-valera/prompts/1sales_context.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/best-valera/prompts/2product_info.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/best-valera/prompts/3objection_handling.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/best-valera/prompts/final_instructions.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/best-valera/prompts/help_message.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/best-valera/prompts/welcome_message.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/best-valera/tests/quick_scenarios.yaml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/best-valera/tests/realistic_scenarios.yaml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/best-valera/tests/scenario_examples.yaml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/best-valera/welcome_files/welcome_file_msg.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/best-valera/welcome_files//320/247/320/265/320/272 /320/273/320/270/321/201/321/202 /320/277/320/276 152/320/244/320/227 /320/270 323/320/244/320/227 /320/264/320/273/321/217 /320/274/320/265/320/264/320/270/321/206/320/270/320/275/321/213.pdf" +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/valera/prompts/2product_info.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/valera/prompts/3objection_handling.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/valera/prompts/final_instructions.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/valera/prompts/help_message.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/valera/prompts/welcome_message.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/valera/tests/quick_scenarios.yaml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/valera/tests/realistic_scenarios.yaml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/valera/tests/scenario_examples.yaml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/valera/welcome_files/welcome_file_msg.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/bots/valera/welcome_files//320/247/320/265/320/272 /320/273/320/270/321/201/321/202 /320/277/320/276 152/320/244/320/227 /320/270 323/320/244/320/227 /320/264/320/273/321/217 /320/274/320/265/320/264/320/270/321/206/320/270/320/275/321/213.pdf" +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/configs/valera/cats//320/224/320/276/320/263/320/276/320/262/320/276/321/200.pdf" +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/configs/valera/cats//320/272/320/276/320/275/320/270.jpg" +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/configs/valera/cats//320/272/320/276/321/202.jpg" +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/configs/valera/cats//320/273/320/265/321/201.jpg" +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/configs/valera/tests/fixes_elina.yaml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/configs/valera/welcome_file//320/247/320/265/320/272 /320/273/320/270/321/201/321/202 /320/277/320/276 152/320/244/320/227 /320/270 323/320/244/320/227 /320/264/320/273/321/217 /320/274/320/265/320/264/320/270/321/206/320/270/320/275/321/213.pdf" +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/create_tag.sh +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/docker-compose.yml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/env.example +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/requirements.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/save_backup.sh +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/save_fixes.sh +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/__init__.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/admin/__init__.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/admin/admin_logic.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/admin/admin_manager.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/admin/admin_migration.sql +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/admin/admin_tester.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/admin/timeout_checker.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/analytics/analytics_manager.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/cli.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/config.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/prompts/1sales_context.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/prompts/2product_info.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/prompts/3objection_handling.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/prompts/final_instructions.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/prompts/help_message.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/prompts/welcome_message.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/reports/test_20250924_064229.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/reports/test_20250924_064335.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/reports/test_20250924_064638.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/tests/quick_scenarios.yaml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/tests/realistic_scenarios.yaml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/tests/scenario_examples.yaml +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/welcome_file/welcome_file_msg.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/configs/growthmed-october-24/welcome_file//320/247/320/265/320/272 /320/273/320/270/321/201/321/202 /320/277/320/276 152/320/244/320/227 /320/270 323/320/244/320/227 /320/264/320/273/321/217 /320/274/320/265/320/264/320/270/321/206/320/270/320/275/321/213.pdf" +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/core/bot_utils.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/core/conversation_manager.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/core/message_sender.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/core/router.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/core/router_manager.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/core/states.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/creation/__init__.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/creation/bot_builder.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/creation/bot_testing.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/database/database_structure.sql +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/database/schema.sql +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/event/__init__.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/handlers/handlers.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/integrations/openai_client.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/message/__init__.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/router/__init__.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/setup_checker.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/supabase/__init__.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/supabase/client.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/utils/__init__.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/utils/debug_routing.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/utils/prompt_loader.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/smart_bot_factory/utm_link_generator.py +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/system_prompt_example.txt +0 -0
- {smart_bot_factory-0.1.8 → smart_bot_factory-0.1.9}/valera.py +0 -0
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: smart-bot-factory
|
|
3
|
+
Version: 0.1.9
|
|
4
|
+
Summary: Библиотека для создания умных чат-ботов
|
|
5
|
+
Author-email: Kopatych <kopatych@example.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: chatbot,cli,openai,supabase,telegram
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Framework :: AsyncIO
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Communications :: Chat
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Requires-Dist: aiofiles>=23.0.0
|
|
24
|
+
Requires-Dist: aiogram>=3.4.1
|
|
25
|
+
Requires-Dist: click>=8.0.0
|
|
26
|
+
Requires-Dist: openai>=1.12.0
|
|
27
|
+
Requires-Dist: project-root-finder>=1.9
|
|
28
|
+
Requires-Dist: python-dotenv>=1.0.1
|
|
29
|
+
Requires-Dist: pytz>=2023.3
|
|
30
|
+
Requires-Dist: pyyaml>=6.0.2
|
|
31
|
+
Requires-Dist: supabase>=2.3.4
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# Smart Bot Factory
|
|
35
|
+
|
|
36
|
+
Современная библиотека для создания умных чат-ботов на Python с использованием OpenAI, Telegram и Supabase.
|
|
37
|
+
|
|
38
|
+
## 🚀 Возможности
|
|
39
|
+
|
|
40
|
+
- **🤖 AI Integration** - Полная интеграция с OpenAI GPT для умных диалогов
|
|
41
|
+
- **📱 Telegram Bot API** - Поддержка через aiogram 3.x
|
|
42
|
+
- **💾 Supabase Backend** - Хранение данных, сессий и аналитики
|
|
43
|
+
- **🎯 Router System** - Модульная система обработчиков событий
|
|
44
|
+
- **⏰ Smart Scheduler** - Умное планирование задач с проверкой активности пользователей
|
|
45
|
+
- **🌍 Global Handlers** - Массовые рассылки и глобальные события
|
|
46
|
+
- **🧪 Testing Suite** - Встроенная система тестирования ботов
|
|
47
|
+
- **🛠️ CLI Tools** - Удобный интерфейс командной строки
|
|
48
|
+
- **👥 Admin Panel** - Система администрирования через Telegram
|
|
49
|
+
- **📊 Analytics** - Встроенная аналитика и отчеты
|
|
50
|
+
|
|
51
|
+
## 📦 Установка
|
|
52
|
+
|
|
53
|
+
### Системные требования
|
|
54
|
+
|
|
55
|
+
Перед установкой убедитесь, что у вас установлено:
|
|
56
|
+
|
|
57
|
+
- **Python 3.9+** (рекомендуется 3.11+)
|
|
58
|
+
- **pip** или **uv** для управления пакетами
|
|
59
|
+
- Доступ к интернету для установки зависимостей
|
|
60
|
+
|
|
61
|
+
### Из PyPI (рекомендуется)
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
pip install smart_bot_factory
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### С помощью uv (современный менеджер пакетов)
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
uv add smart_bot_factory
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Из исходников (для разработки)
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
# Клонируйте репозиторий
|
|
77
|
+
git clone https://github.com/yourusername/chat-bots.git
|
|
78
|
+
cd chat-bots
|
|
79
|
+
|
|
80
|
+
# Установите зависимости через uv
|
|
81
|
+
uv sync
|
|
82
|
+
|
|
83
|
+
# Или через pip
|
|
84
|
+
pip install -e .
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Установка определенной версии
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
pip install smart_bot_factory==0.1.8
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### Проверка установки
|
|
94
|
+
|
|
95
|
+
После установки проверьте доступность CLI:
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
sbf --help
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Вы должны увидеть список доступных команд.
|
|
102
|
+
|
|
103
|
+
### Настройка внешних сервисов
|
|
104
|
+
|
|
105
|
+
Для работы бота вам понадобятся:
|
|
106
|
+
|
|
107
|
+
1. **Telegram Bot Token**
|
|
108
|
+
- Создайте бота через [@BotFather](https://t.me/botfather)
|
|
109
|
+
- Получите токен вида `123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`
|
|
110
|
+
|
|
111
|
+
2. **OpenAI API Key**
|
|
112
|
+
- Зарегистрируйтесь на [platform.openai.com](https://platform.openai.com)
|
|
113
|
+
- Создайте API ключ в разделе API Keys
|
|
114
|
+
- Ключ имеет вид `sk-...`
|
|
115
|
+
|
|
116
|
+
3. **Supabase Project**
|
|
117
|
+
- Создайте проект на [supabase.com](https://supabase.com)
|
|
118
|
+
- Получите URL проекта и `anon` ключ в Project Settings → API
|
|
119
|
+
- Импортируйте SQL схему из `smart_bot_factory/database/schema.sql`
|
|
120
|
+
|
|
121
|
+
## ⚡ Быстрый старт
|
|
122
|
+
|
|
123
|
+
### 1. Создайте нового бота
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
sbf create my-bot
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Это создаст:
|
|
130
|
+
- 📁 `bots/my-bot/` - папка с конфигурацией бота
|
|
131
|
+
- 📄 `my-bot.py` - основной файл запуска
|
|
132
|
+
- ⚙️ `bots/my-bot/.env` - конфигурация окружения
|
|
133
|
+
- 📝 `bots/my-bot/prompts/` - промпты для AI
|
|
134
|
+
- 🧪 `bots/my-bot/tests/` - тестовые сценарии
|
|
135
|
+
|
|
136
|
+
### 2. Настройте переменные окружения
|
|
137
|
+
|
|
138
|
+
Отредактируйте `bots/my-bot/.env`:
|
|
139
|
+
|
|
140
|
+
```env
|
|
141
|
+
# Telegram
|
|
142
|
+
TELEGRAM_BOT_TOKEN=your_bot_token
|
|
143
|
+
|
|
144
|
+
# Supabase
|
|
145
|
+
SUPABASE_URL=https://your-project.supabase.co
|
|
146
|
+
SUPABASE_KEY=your_supabase_key
|
|
147
|
+
|
|
148
|
+
# OpenAI
|
|
149
|
+
OPENAI_API_KEY=sk-your-openai-key
|
|
150
|
+
OPENAI_MODEL=gpt-4o-mini
|
|
151
|
+
|
|
152
|
+
# Администраторы
|
|
153
|
+
ADMIN_TELEGRAM_IDS=123456789,987654321
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### 3. Запустите бота
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
sbf run my-bot
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## 📚 Архитектура
|
|
163
|
+
|
|
164
|
+
### Router System
|
|
165
|
+
|
|
166
|
+
Smart Bot Factory использует систему роутеров для организации обработчиков:
|
|
167
|
+
|
|
168
|
+
```python
|
|
169
|
+
from smart_bot_factory.router import Router
|
|
170
|
+
from smart_bot_factory.message import send_message_by_human
|
|
171
|
+
from smart_bot_factory.creation import BotBuilder
|
|
172
|
+
|
|
173
|
+
# Создаем роутер
|
|
174
|
+
router = Router("my_bot_handlers")
|
|
175
|
+
|
|
176
|
+
# Регистрируем обработчики
|
|
177
|
+
@router.event_handler("appointment_booking", notify=True)
|
|
178
|
+
async def handle_booking(user_id: int, event_data: str):
|
|
179
|
+
"""Обработчик записи на прием"""
|
|
180
|
+
await send_message_by_human(
|
|
181
|
+
user_id=user_id,
|
|
182
|
+
message_text=f"✅ Запись подтверждена! {event_data}"
|
|
183
|
+
)
|
|
184
|
+
return {"status": "success"}
|
|
185
|
+
|
|
186
|
+
# Запуск бота
|
|
187
|
+
async def main():
|
|
188
|
+
bot = BotBuilder("my-bot")
|
|
189
|
+
bot.register_router(router)
|
|
190
|
+
await bot.build()
|
|
191
|
+
await bot.start()
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
### Типы обработчиков
|
|
195
|
+
|
|
196
|
+
#### 1. Event Handlers - Обработчики событий
|
|
197
|
+
|
|
198
|
+
Немедленная обработка событий от AI:
|
|
199
|
+
|
|
200
|
+
```python
|
|
201
|
+
@router.event_handler("phone_collected", notify=True, once_only=True)
|
|
202
|
+
async def handle_phone(user_id: int, event_data: str):
|
|
203
|
+
"""Вызывается когда AI собирает номер телефона"""
|
|
204
|
+
# event_data содержит данные от AI
|
|
205
|
+
phone = parse_phone(event_data)
|
|
206
|
+
|
|
207
|
+
# Сохраняем в CRM
|
|
208
|
+
await save_to_crm(user_id, phone)
|
|
209
|
+
|
|
210
|
+
return {"status": "saved", "phone": phone}
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
**Параметры:**
|
|
214
|
+
- `notify` - уведомлять админов (default: False)
|
|
215
|
+
- `once_only` - выполнить только один раз (default: True)
|
|
216
|
+
|
|
217
|
+
#### 2. Scheduled Tasks - Запланированные задачи
|
|
218
|
+
|
|
219
|
+
Задачи с отложенным выполнением для конкретного пользователя:
|
|
220
|
+
|
|
221
|
+
```python
|
|
222
|
+
@router.schedule_task("send_reminder", delay="2h", smart_check=True)
|
|
223
|
+
async def send_reminder(user_id: int, reminder_text: str):
|
|
224
|
+
"""Отправит напоминание через 2 часа"""
|
|
225
|
+
await send_message_by_human(
|
|
226
|
+
user_id=user_id,
|
|
227
|
+
message_text=f"🔔 {reminder_text}"
|
|
228
|
+
)
|
|
229
|
+
return {"status": "sent"}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
**Параметры:**
|
|
233
|
+
- `delay` - задержка (обязательно): `"1h"`, `"30m"`, `"2h 15m"`, `3600`
|
|
234
|
+
- `smart_check` - умная проверка активности (default: True)
|
|
235
|
+
- `once_only` - выполнить только один раз (default: True)
|
|
236
|
+
- `event_type` - привязка к событию для напоминаний
|
|
237
|
+
|
|
238
|
+
**Smart Check:**
|
|
239
|
+
- Отменяет задачу если пользователь перешел на другой этап
|
|
240
|
+
- Переносит выполнение если пользователь был активен недавно
|
|
241
|
+
- Сохраняет session_id для точного отслеживания
|
|
242
|
+
|
|
243
|
+
#### 3. Global Handlers - Глобальные обработчики
|
|
244
|
+
|
|
245
|
+
Массовые действия для всех пользователей:
|
|
246
|
+
|
|
247
|
+
```python
|
|
248
|
+
@router.global_handler("mass_notification", delay="1h", notify=True)
|
|
249
|
+
async def send_announcement(announcement_text: str):
|
|
250
|
+
"""Отправит анонс всем пользователям через 1 час"""
|
|
251
|
+
from smart_bot_factory.message import send_message_to_users_by_stage
|
|
252
|
+
|
|
253
|
+
await send_message_to_users_by_stage(
|
|
254
|
+
stage="introduction",
|
|
255
|
+
message_text=announcement_text,
|
|
256
|
+
bot_id="my-bot"
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
return {"status": "completed"}
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
**Параметры:**
|
|
263
|
+
- `delay` - задержка (обязательно)
|
|
264
|
+
- `notify` - уведомлять админов (default: False)
|
|
265
|
+
- `once_only` - выполнить только один раз (default: True)
|
|
266
|
+
|
|
267
|
+
### Event-Based Reminders
|
|
268
|
+
|
|
269
|
+
Напоминания о событиях за определенное время:
|
|
270
|
+
|
|
271
|
+
```python
|
|
272
|
+
# Сначала создаем обработчик события
|
|
273
|
+
@router.event_handler("appointment_booking")
|
|
274
|
+
async def handle_booking(user_id: int, event_data: str):
|
|
275
|
+
"""Сохраняет запись: имя, телефон, дата, время"""
|
|
276
|
+
return {"status": "saved", "data": event_data}
|
|
277
|
+
|
|
278
|
+
# Затем создаем напоминание
|
|
279
|
+
@router.schedule_task(
|
|
280
|
+
"appointment_reminder",
|
|
281
|
+
delay="2h",
|
|
282
|
+
event_type="appointment_booking" # Привязка к событию
|
|
283
|
+
)
|
|
284
|
+
async def remind_about_appointment(user_id: int, reminder_text: str):
|
|
285
|
+
"""Отправит напоминание за 2 часа до записи"""
|
|
286
|
+
await send_message_by_human(
|
|
287
|
+
user_id=user_id,
|
|
288
|
+
message_text=f"⏰ Напоминание о записи через 2 часа!"
|
|
289
|
+
)
|
|
290
|
+
return {"status": "sent"}
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
Система автоматически:
|
|
294
|
+
1. Извлечет дату/время из события `appointment_booking`
|
|
295
|
+
2. Вычислит время напоминания (за 2 часа до записи)
|
|
296
|
+
3. Запланирует отправку в правильное время
|
|
297
|
+
|
|
298
|
+
## 🛠️ CLI Команды
|
|
299
|
+
|
|
300
|
+
```bash
|
|
301
|
+
# Создание и управление ботами
|
|
302
|
+
sbf create <bot-id> # Создать нового бота
|
|
303
|
+
sbf create <bot-id> <template> # Создать из шаблона
|
|
304
|
+
sbf copy <source> <new-id> # Копировать существующего бота
|
|
305
|
+
sbf list # Показать всех ботов
|
|
306
|
+
sbf rm <bot-id> # Удалить бота
|
|
307
|
+
|
|
308
|
+
# Запуск
|
|
309
|
+
sbf run <bot-id> # Запустить бота
|
|
310
|
+
|
|
311
|
+
# Тестирование
|
|
312
|
+
sbf test <bot-id> # Запустить все тесты
|
|
313
|
+
sbf test <bot-id> --file quick_scenarios.yaml
|
|
314
|
+
sbf test <bot-id> -v # Подробный вывод
|
|
315
|
+
sbf test <bot-id> --max-concurrent 10
|
|
316
|
+
|
|
317
|
+
# Промпты
|
|
318
|
+
sbf prompts <bot-id> # Список промптов
|
|
319
|
+
sbf prompts <bot-id> --edit welcome_message
|
|
320
|
+
sbf prompts <bot-id> --add new_prompt
|
|
321
|
+
|
|
322
|
+
# Конфигурация
|
|
323
|
+
sbf config <bot-id> # Редактировать .env
|
|
324
|
+
sbf path # Показать путь к проекту
|
|
325
|
+
sbf link # Генератор UTM-ссылок
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
## 📝 Система промптов
|
|
329
|
+
|
|
330
|
+
Промпты хранятся в `bots/<bot-id>/prompts/`:
|
|
331
|
+
|
|
332
|
+
- `welcome_message.txt` - Приветственное сообщение
|
|
333
|
+
- `help_message.txt` - Справка для пользователя
|
|
334
|
+
- `1sales_context.txt` - Контекст продаж
|
|
335
|
+
- `2product_info.txt` - Информация о продукте
|
|
336
|
+
- `3objection_handling.txt` - Работа с возражениями
|
|
337
|
+
- `final_instructions.txt` - Финальные инструкции для AI
|
|
338
|
+
|
|
339
|
+
AI автоматически получает доступ к зарегистрированным обработчикам через промпт.
|
|
340
|
+
|
|
341
|
+
## 🧪 Тестирование
|
|
342
|
+
|
|
343
|
+
Создайте тестовые сценарии в YAML:
|
|
344
|
+
|
|
345
|
+
```yaml
|
|
346
|
+
# bots/my-bot/tests/scenarios.yaml
|
|
347
|
+
scenarios:
|
|
348
|
+
- name: "Запись на прием"
|
|
349
|
+
steps:
|
|
350
|
+
- user: "Привет!"
|
|
351
|
+
expect_stage: "introduction"
|
|
352
|
+
|
|
353
|
+
- user: "Хочу записаться на прием"
|
|
354
|
+
expect_stage: "qualification"
|
|
355
|
+
expect_events:
|
|
356
|
+
- type: "appointment_request"
|
|
357
|
+
|
|
358
|
+
- user: "Меня зовут Иван, +79991234567, завтра в 15:00"
|
|
359
|
+
expect_events:
|
|
360
|
+
- type: "appointment_booking"
|
|
361
|
+
- type: "appointment_reminder" # Должно запланироваться
|
|
362
|
+
expect_quality: ">= 8"
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
Запуск:
|
|
366
|
+
```bash
|
|
367
|
+
sbf test my-bot --file scenarios.yaml -v
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
## 💬 Отправка сообщений
|
|
371
|
+
|
|
372
|
+
### Отправка пользователю
|
|
373
|
+
|
|
374
|
+
```python
|
|
375
|
+
from smart_bot_factory.message import send_message_by_human
|
|
376
|
+
|
|
377
|
+
await send_message_by_human(
|
|
378
|
+
user_id=123456789,
|
|
379
|
+
message_text="Привет! Это сообщение от системы",
|
|
380
|
+
session_id="optional-session-id"
|
|
381
|
+
)
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
### Массовая рассылка по этапу
|
|
385
|
+
|
|
386
|
+
```python
|
|
387
|
+
from smart_bot_factory.message import send_message_to_users_by_stage
|
|
388
|
+
|
|
389
|
+
await send_message_to_users_by_stage(
|
|
390
|
+
stage="introduction",
|
|
391
|
+
message_text="📢 Важное объявление!",
|
|
392
|
+
bot_id="my-bot"
|
|
393
|
+
)
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
## 🗄️ База данных
|
|
397
|
+
|
|
398
|
+
Smart Bot Factory использует Supabase со следующими таблицами:
|
|
399
|
+
|
|
400
|
+
- `sales_users` - Пользователи
|
|
401
|
+
- `sales_chat_sessions` - Сессии диалогов
|
|
402
|
+
- `sales_chat_messages` - История сообщений
|
|
403
|
+
- `scheduled_events` - Запланированные события и задачи
|
|
404
|
+
- `admin_sessions` - Сессии администраторов
|
|
405
|
+
|
|
406
|
+
SQL схема доступна в `smart_bot_factory/database/`.
|
|
407
|
+
|
|
408
|
+
## 👥 Система администрирования
|
|
409
|
+
|
|
410
|
+
Добавьте ID администраторов в `.env`:
|
|
411
|
+
|
|
412
|
+
```env
|
|
413
|
+
ADMIN_TELEGRAM_IDS=123456789,987654321
|
|
414
|
+
ADMIN_SESSION_TIMEOUT_MINUTES=30
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
Админы получают:
|
|
418
|
+
- 📊 Статистику и аналитику
|
|
419
|
+
- 🔔 Уведомления о важных событиях (если `notify=True`)
|
|
420
|
+
- 🛠️ Доступ к специальным командам
|
|
421
|
+
|
|
422
|
+
## 🔧 Продвинутое использование
|
|
423
|
+
|
|
424
|
+
### Множественные роутеры
|
|
425
|
+
|
|
426
|
+
```python
|
|
427
|
+
# handlers/main.py
|
|
428
|
+
main_router = Router("main")
|
|
429
|
+
|
|
430
|
+
# handlers/admin.py
|
|
431
|
+
admin_router = Router("admin")
|
|
432
|
+
|
|
433
|
+
# app.py
|
|
434
|
+
bot = BotBuilder("my-bot")
|
|
435
|
+
bot.register_router(main_router)
|
|
436
|
+
bot.register_router(admin_router)
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
### Вложенные роутеры
|
|
440
|
+
|
|
441
|
+
```python
|
|
442
|
+
main_router = Router("main")
|
|
443
|
+
payments_router = Router("payments")
|
|
444
|
+
|
|
445
|
+
# Включаем роутер платежей в основной
|
|
446
|
+
main_router.include_router(payments_router)
|
|
447
|
+
|
|
448
|
+
bot.register_router(main_router)
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
### Работа с клиентами
|
|
452
|
+
|
|
453
|
+
```python
|
|
454
|
+
from smart_bot_factory.supabase import SupabaseClient
|
|
455
|
+
|
|
456
|
+
# Создаем клиент для вашего бота
|
|
457
|
+
supabase = SupabaseClient("my-bot")
|
|
458
|
+
|
|
459
|
+
# Используем напрямую
|
|
460
|
+
users = supabase.client.table('sales_users').select('*').eq('bot_id', 'my-bot').execute()
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
## 📊 Структура проекта
|
|
464
|
+
|
|
465
|
+
```
|
|
466
|
+
my-project/
|
|
467
|
+
├── bots/ # Папка с ботами
|
|
468
|
+
│ ├── my-bot/
|
|
469
|
+
│ │ ├── .env # Конфигурация
|
|
470
|
+
│ │ ├── prompts/ # AI промпты
|
|
471
|
+
│ │ ├── tests/ # Тестовые сценарии
|
|
472
|
+
│ │ ├── files/ # Файлы бота
|
|
473
|
+
│ │ ├── welcome_files/ # Приветственные файлы
|
|
474
|
+
│ │ └── reports/ # Отчеты тестов
|
|
475
|
+
│ └── another-bot/
|
|
476
|
+
│ └── ...
|
|
477
|
+
├── my-bot.py # Основной файл запуска
|
|
478
|
+
├── another-bot.py
|
|
479
|
+
└── .env # Глобальная конфигурация (опционально)
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
## 🔄 Примеры
|
|
483
|
+
|
|
484
|
+
### Полный пример бота
|
|
485
|
+
|
|
486
|
+
```python
|
|
487
|
+
import asyncio
|
|
488
|
+
|
|
489
|
+
from smart_bot_factory.router import Router
|
|
490
|
+
from smart_bot_factory.message import send_message_by_human, send_message_to_users_by_stage
|
|
491
|
+
from smart_bot_factory.supabase import SupabaseClient
|
|
492
|
+
from smart_bot_factory.creation import BotBuilder
|
|
493
|
+
|
|
494
|
+
# Инициализация
|
|
495
|
+
router = Router("medical_bot")
|
|
496
|
+
supabase_client = SupabaseClient("medical-bot")
|
|
497
|
+
|
|
498
|
+
# Обработчик записи на прием
|
|
499
|
+
@router.event_handler("appointment_booking", notify=True)
|
|
500
|
+
async def handle_appointment(user_id: int, event_data: str):
|
|
501
|
+
"""Обрабатывает запись на прием к врачу"""
|
|
502
|
+
# event_data: "имя: Иван, телефон: +79991234567, дата: 2025-10-15, время: 14:00"
|
|
503
|
+
|
|
504
|
+
await send_message_by_human(
|
|
505
|
+
user_id=user_id,
|
|
506
|
+
message_text="✅ Запись подтверждена! Ждем вас."
|
|
507
|
+
)
|
|
508
|
+
|
|
509
|
+
return {"status": "success", "data": event_data}
|
|
510
|
+
|
|
511
|
+
# Напоминание за 2 часа до приема
|
|
512
|
+
@router.schedule_task(
|
|
513
|
+
"appointment_reminder",
|
|
514
|
+
delay="2h",
|
|
515
|
+
event_type="appointment_booking"
|
|
516
|
+
)
|
|
517
|
+
async def remind_before_appointment(user_id: int, reminder_text: str):
|
|
518
|
+
"""Напоминание о записи"""
|
|
519
|
+
await send_message_by_human(
|
|
520
|
+
user_id=user_id,
|
|
521
|
+
message_text="⏰ Напоминаем о вашей записи через 2 часа!"
|
|
522
|
+
)
|
|
523
|
+
return {"status": "sent"}
|
|
524
|
+
|
|
525
|
+
# Ночной дайджест для всех
|
|
526
|
+
@router.global_handler("daily_digest", delay="24h")
|
|
527
|
+
async def send_daily_digest(digest_text: str):
|
|
528
|
+
"""Отправляет ежедневный дайджест всем активным пользователям"""
|
|
529
|
+
await send_message_to_users_by_stage(
|
|
530
|
+
stage="active",
|
|
531
|
+
message_text=f"📊 Дайджест дня:\n\n{digest_text}",
|
|
532
|
+
bot_id="medical-bot"
|
|
533
|
+
)
|
|
534
|
+
|
|
535
|
+
# Запуск
|
|
536
|
+
async def main():
|
|
537
|
+
bot = BotBuilder("medical-bot")
|
|
538
|
+
bot.register_router(router)
|
|
539
|
+
await bot.build()
|
|
540
|
+
await bot.start()
|
|
541
|
+
|
|
542
|
+
if __name__ == "__main__":
|
|
543
|
+
asyncio.run(main())
|
|
544
|
+
```
|
|
545
|
+
|
|
546
|
+
## 🐛 Отладка
|
|
547
|
+
|
|
548
|
+
Включите режим отладки в `.env`:
|
|
549
|
+
|
|
550
|
+
```env
|
|
551
|
+
DEBUG_MODE=true
|
|
552
|
+
LOG_LEVEL=DEBUG
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
Это покажет:
|
|
556
|
+
- JSON ответы от AI
|
|
557
|
+
- Детальные логи обработки
|
|
558
|
+
- Информацию о роутерах и обработчиках
|
|
559
|
+
|
|
560
|
+
## 📋 Требования
|
|
561
|
+
|
|
562
|
+
### Системные
|
|
563
|
+
- Python 3.9+ (рекомендуется 3.11+)
|
|
564
|
+
- pip или uv для управления пакетами
|
|
565
|
+
|
|
566
|
+
### Основные зависимости
|
|
567
|
+
- aiogram 3.4.1+ - Telegram Bot API
|
|
568
|
+
- supabase 2.3.4+ - База данных
|
|
569
|
+
- openai 1.12.0+ - AI модель
|
|
570
|
+
- click 8.0.0+ - CLI интерфейс
|
|
571
|
+
- python-dotenv 1.0.1+ - Управление переменными окружения
|
|
572
|
+
|
|
573
|
+
Все зависимости устанавливаются автоматически при установке библиотеки.
|
|
574
|
+
|
|
575
|
+
### Внешние сервисы
|
|
576
|
+
- Telegram Bot Token ([@BotFather](https://t.me/botfather))
|
|
577
|
+
- OpenAI API Key ([platform.openai.com](https://platform.openai.com))
|
|
578
|
+
- Supabase Project ([supabase.com](https://supabase.com))
|
|
579
|
+
|
|
580
|
+
Подробнее см. раздел [Установка](#-установка).
|
|
581
|
+
|
|
582
|
+
## 🤝 Вклад в проект
|
|
583
|
+
|
|
584
|
+
Мы приветствуем вклад в развитие проекта!
|
|
585
|
+
|
|
586
|
+
## 📄 Лицензия
|
|
587
|
+
|
|
588
|
+
MIT License - см. [LICENSE](LICENSE)
|
|
589
|
+
|
|
590
|
+
## 🔗 Полезные ссылки
|
|
591
|
+
|
|
592
|
+
- [Документация Supabase](https://supabase.com/docs)
|
|
593
|
+
- [Документация OpenAI](https://platform.openai.com/docs)
|
|
594
|
+
- [Документация aiogram](https://docs.aiogram.dev/)
|
|
595
|
+
|
|
596
|
+
## 💡 Поддержка
|
|
597
|
+
|
|
598
|
+
Если у вас возникли вопросы или проблемы, создайте issue в репозитории.
|
|
599
|
+
|
|
600
|
+
---
|
|
601
|
+
|
|
602
|
+
Сделано с ❤️ для создания умных ботов
|