smart-bot-factory 0.1.8__py3-none-any.whl → 0.1.9__py3-none-any.whl

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.

@@ -1153,7 +1153,7 @@ async def background_event_processor():
1153
1153
  logger.error(f"❌ Ошибка обработки события {event['id']}: {e}")
1154
1154
  await update_event_result(event['id'], 'failed', None, str(e))
1155
1155
 
1156
- await asyncio.sleep(30)
1156
+ await asyncio.sleep(60)
1157
1157
 
1158
1158
  except Exception as e:
1159
1159
  logger.error(f"❌ Ошибка в фоновом процессоре: {e}")
@@ -805,31 +805,21 @@ class SupabaseClient:
805
805
  return {}
806
806
 
807
807
  async def get_user_last_message_info(self, user_id: int) -> Optional[Dict[str, Any]]:
808
- """Получает информацию о последнем сообщении пользователя"""
808
+ """Получает информацию о последней активности пользователя из сессии"""
809
809
  try:
810
- # Получаем последнее сообщение пользователя
811
- response = self.client.table('sales_messages').select(
812
- 'id', 'created_at', 'session_id', 'sender_type'
813
- ).eq('sender_telegram_id', user_id).order('created_at', desc=True).limit(1).execute()
810
+ # Получаем последнюю сессию пользователя
811
+ response = self.client.table('sales_chat_sessions').select(
812
+ 'id', 'current_stage', 'created_at', 'updated_at'
813
+ ).eq('user_id', user_id).order('updated_at', desc=True).limit(1).execute()
814
814
 
815
815
  if not response.data:
816
816
  return None
817
817
 
818
- last_message = response.data[0]
819
-
820
- # Получаем информацию о сессии
821
- session_response = self.client.table('sales_chat_sessions').select(
822
- 'id', 'current_stage', 'updated_at'
823
- ).eq('id', last_message['session_id']).execute()
824
-
825
- if not session_response.data:
826
- return None
827
-
828
- session = session_response.data[0]
818
+ session = response.data[0]
829
819
 
830
820
  return {
831
- 'last_message_at': last_message['created_at'],
832
- 'session_id': last_message['session_id'],
821
+ 'last_message_at': session['updated_at'],
822
+ 'session_id': session['id'],
833
823
  'current_stage': session['current_stage'],
834
824
  'session_updated_at': session['updated_at']
835
825
  }
@@ -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
+ Сделано с ❤️ для создания умных ботов
@@ -26,7 +26,7 @@ smart_bot_factory/configs/growthmed-october-24/welcome_file/welcome_file_msg.txt
26
26
  smart_bot_factory/configs/growthmed-october-24/welcome_file/Чек лист по 152ФЗ и 323ФЗ для медицины.pdf,sha256=BiAiQHNnQXJPMsks9AeL6s0beEjRFkRMJLMlAn4WorA,5284954
27
27
  smart_bot_factory/core/bot_utils.py,sha256=XmwQ31LOpE_Wudx4OO4tlnVwse3YagakwpgN2cZC5SQ,41085
28
28
  smart_bot_factory/core/conversation_manager.py,sha256=eoHL7MCEz68DRvTVwRwZgf2PWwGv4T6J9D-I-thETi8,28289
29
- smart_bot_factory/core/decorators.py,sha256=BuG5nyDXnz7Gp0W7eQOEXxkdpkqgGwdu-7QVgBJXRYs,68647
29
+ smart_bot_factory/core/decorators.py,sha256=xQCtr5SOLqqmEzaxrDf_sfxWQouIG7riI6Sa_jqGlcg,68647
30
30
  smart_bot_factory/core/message_sender.py,sha256=7uZlMw7bdLb_2eokANUxyP4HomVQV7T2mrl4SBTfqNM,19134
31
31
  smart_bot_factory/core/router.py,sha256=Ly2Kj6T9stu2UmE__3CvMvN8Rl1Ipo-SrsbTsiPSssA,11469
32
32
  smart_bot_factory/core/router_manager.py,sha256=qncd57qhqXBV42FBEQ8Wl7aar8S7WZnfSC4EQ1BIr0w,9617
@@ -39,7 +39,7 @@ smart_bot_factory/database/schema.sql,sha256=-6kOmA9QnSkUtmGI2iQRbTvbdiqOhEOQcuz
39
39
  smart_bot_factory/event/__init__.py,sha256=hPL449RULIOB-OXv1ZbGNiHctAYaOMUqhSWGPrDHYBM,212
40
40
  smart_bot_factory/handlers/handlers.py,sha256=YH8xG0tDcb7uxZXI4socXURzc-y57_FEQ6GqTgYcM5Q,37603
41
41
  smart_bot_factory/integrations/openai_client.py,sha256=aMcDrKO0GEx3ZSVEOGDeDtFCDWSXs6biUfgrbRK8yTU,23180
42
- smart_bot_factory/integrations/supabase_client.py,sha256=FLYD4gOSBAAukzExImFB4NLlNmBJPgI3d24Vht0A_uQ,45074
42
+ smart_bot_factory/integrations/supabase_client.py,sha256=AfALLZdDYeMWHLJw6POTGiBd-sH3i03oT6tT7m9C28I,44644
43
43
  smart_bot_factory/message/__init__.py,sha256=6QvjdfF99venyDB9udZv9WDNjIHJLNuaVhYdTK3a44A,282
44
44
  smart_bot_factory/router/__init__.py,sha256=fLXSXfa-MaI9ickXoqha3PqpjxunsNLyVNlHIoIbr1c,115
45
45
  smart_bot_factory/supabase/__init__.py,sha256=XmZP6yM9ffERM5ddAWyJnrNzEhCYtMu3AcjVCi1rOf8,179
@@ -47,8 +47,8 @@ smart_bot_factory/supabase/client.py,sha256=8_-I3kxZQlKQElI4cTUjNGYcqlyIyEkSrUZa
47
47
  smart_bot_factory/utils/__init__.py,sha256=5zNjw491bj5VkOhoEAwh2hjmv8nldyDOTrG7pbGpz6A,285
48
48
  smart_bot_factory/utils/debug_routing.py,sha256=BOoDhKBg7UXe5uHQxRk3TSfPfLPOFqt0N7lAo6kjCOo,4719
49
49
  smart_bot_factory/utils/prompt_loader.py,sha256=JSn7CsWnToSbHYtURdeuZn7ectyDqQGrPGHN2ixIGkw,19930
50
- smart_bot_factory-0.1.8.dist-info/METADATA,sha256=6JJ-TmhTcre_FFDNiHfqGOvQnG90UXZm1UZB172mjIQ,3528
51
- smart_bot_factory-0.1.8.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
52
- smart_bot_factory-0.1.8.dist-info/entry_points.txt,sha256=ybKEAI0WSb7WoRiey7QE-HHfn88UGV7nxLDxXq7b7SU,50
53
- smart_bot_factory-0.1.8.dist-info/licenses/LICENSE,sha256=OrK3cwdUTzNzIhJvSPtJaVMoYIyC_sSx5EFE_FDMvGs,1092
54
- smart_bot_factory-0.1.8.dist-info/RECORD,,
50
+ smart_bot_factory-0.1.9.dist-info/METADATA,sha256=ViqO05vBPd-Qz6kQ2imVmUqePKRGUaOeyBCGpxG4VUk,20494
51
+ smart_bot_factory-0.1.9.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
52
+ smart_bot_factory-0.1.9.dist-info/entry_points.txt,sha256=ybKEAI0WSb7WoRiey7QE-HHfn88UGV7nxLDxXq7b7SU,50
53
+ smart_bot_factory-0.1.9.dist-info/licenses/LICENSE,sha256=OrK3cwdUTzNzIhJvSPtJaVMoYIyC_sSx5EFE_FDMvGs,1092
54
+ smart_bot_factory-0.1.9.dist-info/RECORD,,
@@ -1,126 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: smart-bot-factory
3
- Version: 0.1.8
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
- Библиотека для создания умных чат-ботов с использованием OpenAI, Telegram и Supabase.
37
-
38
- ## Установка
39
-
40
- ```bash
41
- pip install smart-bot-factory
42
- ```
43
-
44
- ## Быстрый старт
45
-
46
- 1. Создайте нового бота:
47
- ```bash
48
- sbf create my-bot
49
- ```
50
-
51
- 2. Настройте конфигурацию в `bots/my-bot/.env`
52
-
53
- 3. Запустите бота:
54
- ```bash
55
- sbf run my-bot
56
- ```
57
-
58
- ## Возможности
59
-
60
- - 🤖 Интеграция с OpenAI GPT для умных ответов
61
- - 📱 Поддержка Telegram Bot API через aiogram
62
- - 💾 Хранение данных в Supabase
63
- - 🔄 Система событий и обработчиков
64
- - ⏰ Планировщик задач
65
- - 🧪 Встроенная система тестирования
66
- - 📝 Управление промптами
67
- - 🛠️ Удобный CLI интерфейс
68
-
69
- ## CLI команды
70
-
71
- ```bash
72
- # Создать нового бота
73
- sbf create my-bot
74
-
75
- # Запустить бота
76
- sbf run my-bot
77
-
78
- # Показать список ботов
79
- sbf list
80
-
81
- # Управление промптами
82
- sbf prompts my-bot --list
83
- sbf prompts my-bot --edit welcome_message
84
- sbf prompts my-bot --add new_prompt
85
-
86
- # Запустить тесты
87
- sbf test my-bot
88
- ```
89
-
90
- ## Пример использования
91
-
92
- ```python
93
- from smart_bot_factory import BotBuilder, event_handler, schedule_task
94
-
95
- # Обработчик события
96
- @event_handler("book_appointment", "Запись на прием")
97
- async def handle_booking(user_id: int, event_data: dict):
98
- # Логика обработки записи на прием
99
- return {"status": "success"}
100
-
101
- # Запланированная задача
102
- @schedule_task("send_reminder", "Отправка напоминания")
103
- async def send_reminder(user_id: int, message: str):
104
- # Логика отправки напоминания
105
- return {"status": "sent"}
106
-
107
- # Запуск бота
108
- async def main():
109
- bot = BotBuilder("my-bot")
110
- await bot.build()
111
- await bot.start()
112
-
113
- if __name__ == "__main__":
114
- asyncio.run(main())
115
- ```
116
-
117
- ## Требования
118
-
119
- - Python 3.9+
120
- - OpenAI API ключ
121
- - Telegram Bot Token
122
- - Supabase проект
123
-
124
- ## Лицензия
125
-
126
- MIT