smart-bot-factory 1.1.1__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.
Files changed (73) hide show
  1. smart_bot_factory/__init__.py +3 -0
  2. smart_bot_factory/admin/__init__.py +18 -0
  3. smart_bot_factory/admin/admin_events.py +1223 -0
  4. smart_bot_factory/admin/admin_logic.py +553 -0
  5. smart_bot_factory/admin/admin_manager.py +156 -0
  6. smart_bot_factory/admin/admin_tester.py +157 -0
  7. smart_bot_factory/admin/timeout_checker.py +547 -0
  8. smart_bot_factory/aiogram_calendar/__init__.py +14 -0
  9. smart_bot_factory/aiogram_calendar/common.py +64 -0
  10. smart_bot_factory/aiogram_calendar/dialog_calendar.py +259 -0
  11. smart_bot_factory/aiogram_calendar/schemas.py +99 -0
  12. smart_bot_factory/aiogram_calendar/simple_calendar.py +224 -0
  13. smart_bot_factory/analytics/analytics_manager.py +414 -0
  14. smart_bot_factory/cli.py +806 -0
  15. smart_bot_factory/config.py +258 -0
  16. smart_bot_factory/configs/growthmed-october-24/prompts/1sales_context.txt +16 -0
  17. smart_bot_factory/configs/growthmed-october-24/prompts/2product_info.txt +582 -0
  18. smart_bot_factory/configs/growthmed-october-24/prompts/3objection_handling.txt +66 -0
  19. smart_bot_factory/configs/growthmed-october-24/prompts/final_instructions.txt +212 -0
  20. smart_bot_factory/configs/growthmed-october-24/prompts/help_message.txt +28 -0
  21. smart_bot_factory/configs/growthmed-october-24/prompts/welcome_message.txt +8 -0
  22. smart_bot_factory/configs/growthmed-october-24/reports/test_20250924_064229.txt +818 -0
  23. smart_bot_factory/configs/growthmed-october-24/reports/test_20250924_064335.txt +32 -0
  24. smart_bot_factory/configs/growthmed-october-24/reports/test_20250924_064638.txt +35 -0
  25. smart_bot_factory/configs/growthmed-october-24/tests/quick_scenarios.yaml +133 -0
  26. smart_bot_factory/configs/growthmed-october-24/tests/realistic_scenarios.yaml +108 -0
  27. smart_bot_factory/configs/growthmed-october-24/tests/scenario_examples.yaml +46 -0
  28. smart_bot_factory/configs/growthmed-october-24/welcome_file/welcome_file_msg.txt +16 -0
  29. smart_bot_factory/configs/growthmed-october-24/welcome_file//342/225/250/320/267/342/225/250/342/225/241/342/225/250/342/225/221 /342/225/250/342/225/227/342/225/250/342/225/225/342/225/244/320/221/342/225/244/320/222 /342/225/250/342/224/220/342/225/250/342/225/233 152/342/225/250/320/264/342/225/250/320/247 /342/225/250/342/225/225 323/342/225/250/320/264/342/225/250/320/247 /342/225/250/342/224/244/342/225/250/342/225/227/342/225/244/320/237 /342/225/250/342/225/235/342/225/250/342/225/241/342/225/250/342/224/244/342/225/250/342/225/225/342/225/244/320/226/342/225/250/342/225/225/342/225/250/342/225/234/342/225/244/320/233.pdf +0 -0
  30. smart_bot_factory/core/bot_utils.py +1108 -0
  31. smart_bot_factory/core/conversation_manager.py +653 -0
  32. smart_bot_factory/core/decorators.py +2464 -0
  33. smart_bot_factory/core/message_sender.py +729 -0
  34. smart_bot_factory/core/router.py +347 -0
  35. smart_bot_factory/core/router_manager.py +218 -0
  36. smart_bot_factory/core/states.py +27 -0
  37. smart_bot_factory/creation/__init__.py +7 -0
  38. smart_bot_factory/creation/bot_builder.py +1093 -0
  39. smart_bot_factory/creation/bot_testing.py +1122 -0
  40. smart_bot_factory/dashboard/__init__.py +3 -0
  41. smart_bot_factory/event/__init__.py +7 -0
  42. smart_bot_factory/handlers/handlers.py +2013 -0
  43. smart_bot_factory/integrations/langchain_openai.py +542 -0
  44. smart_bot_factory/integrations/openai_client.py +513 -0
  45. smart_bot_factory/integrations/supabase_client.py +1678 -0
  46. smart_bot_factory/memory/__init__.py +8 -0
  47. smart_bot_factory/memory/memory_manager.py +299 -0
  48. smart_bot_factory/memory/static_memory.py +214 -0
  49. smart_bot_factory/message/__init__.py +56 -0
  50. smart_bot_factory/rag/__init__.py +5 -0
  51. smart_bot_factory/rag/decorators.py +29 -0
  52. smart_bot_factory/rag/router.py +54 -0
  53. smart_bot_factory/rag/templates/__init__.py +3 -0
  54. smart_bot_factory/rag/templates/create_table.sql +7 -0
  55. smart_bot_factory/rag/templates/create_table_and_function_template.py +94 -0
  56. smart_bot_factory/rag/templates/match_function.sql +61 -0
  57. smart_bot_factory/rag/templates/match_services_template.py +82 -0
  58. smart_bot_factory/rag/vectorstore.py +449 -0
  59. smart_bot_factory/router/__init__.py +10 -0
  60. smart_bot_factory/setup_checker.py +512 -0
  61. smart_bot_factory/supabase/__init__.py +7 -0
  62. smart_bot_factory/supabase/client.py +631 -0
  63. smart_bot_factory/utils/__init__.py +11 -0
  64. smart_bot_factory/utils/debug_routing.py +114 -0
  65. smart_bot_factory/utils/prompt_loader.py +529 -0
  66. smart_bot_factory/utils/tool_router.py +68 -0
  67. smart_bot_factory/utils/user_prompt_loader.py +55 -0
  68. smart_bot_factory/utm_link_generator.py +123 -0
  69. smart_bot_factory-1.1.1.dist-info/METADATA +1135 -0
  70. smart_bot_factory-1.1.1.dist-info/RECORD +73 -0
  71. smart_bot_factory-1.1.1.dist-info/WHEEL +4 -0
  72. smart_bot_factory-1.1.1.dist-info/entry_points.txt +2 -0
  73. smart_bot_factory-1.1.1.dist-info/licenses/LICENSE +24 -0
@@ -0,0 +1,68 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from typing import Any, Callable, Iterable, List
5
+
6
+ from langchain.tools import tool as langchain_tool
7
+ from langchain_core.tools import BaseTool
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class ToolRouter:
13
+ """
14
+ Универсальный роутер для сбора и регистрации LangChain-инструментов.
15
+ """
16
+
17
+ def __init__(self, name: str = "tools"):
18
+ self.name = name
19
+ self._tools: List[BaseTool] = []
20
+
21
+ def tool(self, *tool_args: Any, **tool_kwargs: Any):
22
+ """
23
+ Декоратор для регистрации функции как инструмента LangChain.
24
+
25
+ Пример:
26
+ tool_router = ToolRouter("common")
27
+
28
+ @tool_router.tool
29
+ def ping() -> str:
30
+ return "pong"
31
+ """
32
+
33
+ if tool_args and callable(tool_args[0]) and not tool_kwargs:
34
+ func = tool_args[0]
35
+ tool_obj = langchain_tool(func)
36
+ self.add_tool(tool_obj)
37
+ return tool_obj
38
+
39
+ def decorator(func: Callable[..., Any]):
40
+ tool_obj = langchain_tool(*tool_args, **tool_kwargs)(func)
41
+ self.add_tool(tool_obj)
42
+ return tool_obj
43
+
44
+ return decorator
45
+
46
+ def add_tool(self, tool: BaseTool) -> BaseTool:
47
+ if tool not in self._tools:
48
+ self._tools.append(tool)
49
+ logger.debug("🔧 ToolRouter %s: добавлен инструмент %s", self.name, getattr(tool, "name", tool))
50
+ return tool
51
+
52
+ def extend(self, tools: Iterable[BaseTool]) -> None:
53
+ for tool in tools:
54
+ self.add_tool(tool)
55
+
56
+ def get_tools(self) -> List[BaseTool]:
57
+ return list(self._tools)
58
+
59
+ def register_to(self, bot_builder) -> None:
60
+ tools = self.get_tools()
61
+ if not tools:
62
+ logger.warning("⚠️ ToolRouter %s не содержит инструментов для регистрации", self.name)
63
+ return
64
+ bot_builder.register_tool_set(self)
65
+
66
+
67
+ __all__ = ["ToolRouter"]
68
+
@@ -0,0 +1,55 @@
1
+ """
2
+ UserPromptLoader - упрощенный PromptLoader для пользователей библиотеки
3
+ с автоматическим поиском prompts_dir от корня проекта
4
+ """
5
+
6
+ import logging
7
+
8
+ from .prompt_loader import PromptLoader
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class UserPromptLoader(PromptLoader):
14
+ """
15
+ PromptLoader для пользователей библиотеки с автоматическим поиском prompts_dir
16
+
17
+ Автоматически находит папку prompts для указанного бота от корня проекта
18
+ Наследуется от базового PromptLoader - все методы доступны
19
+ """
20
+
21
+ def __init__(self, bot_id: str, prompts_subdir: str = "prompts"):
22
+ """
23
+ Инициализация загрузчика промптов с автоматическим поиском
24
+
25
+ Args:
26
+ bot_id: Идентификатор бота
27
+ prompts_subdir: Подпапка с промптами (по умолчанию "prompts")
28
+
29
+ Example:
30
+ # Автоматически найдет bots/my-bot/prompts
31
+ loader = UserPromptLoader("my-bot")
32
+
33
+ # Или кастомную подпапку
34
+ loader = UserPromptLoader("my-bot", "custom_prompts")
35
+
36
+ # Наследование для кастомизации
37
+ class MyLoader(UserPromptLoader):
38
+ def __init__(self, bot_id):
39
+ super().__init__(bot_id)
40
+ # Добавить свою логику
41
+ self.extra_file = self.prompts_dir / 'extra.txt'
42
+ """
43
+ from project_root_finder import root
44
+
45
+ # Автоматически определяем путь к промптам
46
+ prompts_dir = root / "bots" / bot_id / prompts_subdir
47
+
48
+ if not prompts_dir.exists():
49
+ logger.warning(f"⚠️ Папка промптов не найдена: {prompts_dir}")
50
+ logger.warning(" Создайте папку или проверьте bot_id")
51
+
52
+ # Вызываем базовую инициализацию
53
+ super().__init__(str(prompts_dir))
54
+
55
+ logger.info(f"✅ UserPromptLoader создан для bot_id '{bot_id}': {prompts_dir}")
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Генератор UTM-ссылок для Telegram ботов
4
+ Создает ссылки в формате: @https://t.me/bot?start=source-vk_campaign-summer2025
5
+ """
6
+
7
+
8
+ def get_user_input():
9
+ """Получает данные от пользователя через консоль"""
10
+ print("🔗 Генератор UTM-ссылок для Telegram")
11
+ print("=" * 50)
12
+
13
+ # Основные параметры
14
+ bot_username = input("Введите username бота (без @): ").strip()
15
+ if not bot_username:
16
+ print("❌ Username бота обязателен!")
17
+ return None
18
+
19
+ print("\n📊 Введите UTM-метки (нажмите Enter для пропуска):")
20
+
21
+ # UTM параметры (соответствуют полям в базе данных)
22
+ utm_source = input("utm_source (источник): ").strip()
23
+ utm_medium = input("utm_medium (канал): ").strip()
24
+ utm_campaign = input("utm_campaign (кампания): ").strip()
25
+ utm_content = input("utm_content (контент): ").strip()
26
+ utm_term = input("utm_term (ключевое слово): ").strip()
27
+
28
+ print("\n🎯 Сегментация (нажмите Enter для пропуска):")
29
+ segment = input("seg (сегмент): ").strip()
30
+
31
+ return {
32
+ "bot_username": bot_username,
33
+ "utm_source": utm_source,
34
+ "utm_medium": utm_medium,
35
+ "utm_campaign": utm_campaign,
36
+ "utm_content": utm_content,
37
+ "utm_term": utm_term,
38
+ "segment": segment,
39
+ }
40
+
41
+
42
+ def create_utm_string(utm_data):
43
+ """Создает строку UTM параметров в формате source-vk_campaign-summer2025_seg-premium"""
44
+ utm_parts = []
45
+
46
+ # Маппинг полей базы данных на формат без префикса utm
47
+ field_mapping = {
48
+ "utm_source": "source",
49
+ "utm_medium": "medium",
50
+ "utm_campaign": "campaign",
51
+ "utm_content": "content",
52
+ "utm_term": "term",
53
+ }
54
+
55
+ for db_field, utm_field in field_mapping.items():
56
+ value = utm_data.get(db_field)
57
+ if value:
58
+ utm_parts.append(f"{utm_field}-{value}")
59
+
60
+ # Добавляем сегмент, если указан
61
+ segment = utm_data.get("segment")
62
+ if segment:
63
+ utm_parts.append(f"seg-{segment}")
64
+
65
+ return "_".join(utm_parts)
66
+
67
+
68
+ def generate_telegram_link(bot_username, utm_string):
69
+ """Генерирует полную ссылку на Telegram бота"""
70
+ return f"https://t.me/{bot_username}?start={utm_string}"
71
+
72
+
73
+ def check_size_and_validate(utm_string):
74
+ """Проверяет размер строки после start= и валидирует"""
75
+ MAX_SIZE = 64
76
+
77
+ if len(utm_string) > MAX_SIZE:
78
+ return (
79
+ False,
80
+ f"Строка слишком большая: {len(utm_string)} символов (максимум {MAX_SIZE})",
81
+ )
82
+
83
+ return True, f"Размер OK: {len(utm_string)} символов"
84
+
85
+
86
+ def main():
87
+ """Основная функция"""
88
+ try:
89
+ # Получаем данные от пользователя
90
+ data = get_user_input()
91
+ if not data:
92
+ return
93
+
94
+ # Создаем UTM строку
95
+ utm_string = create_utm_string(data)
96
+
97
+ if not utm_string:
98
+ print("❌ Не указано ни одной UTM-метки!")
99
+ return
100
+
101
+ # Проверяем размер
102
+ is_valid, size_message = check_size_and_validate(utm_string)
103
+
104
+ print(f"\n📏 {size_message}")
105
+
106
+ if not is_valid:
107
+ print("❌ Ссылка превышает максимальный размер!")
108
+ print("💡 Сократите значения UTM-меток или уберите менее важные")
109
+ return
110
+
111
+ # Генерируем и выводим ссылку
112
+ telegram_link = generate_telegram_link(data["bot_username"], utm_string)
113
+
114
+ print("\n✅ Сгенерированная ссылка:")
115
+ print(f"🔗 {telegram_link}")
116
+ except KeyboardInterrupt:
117
+ print("\n\n👋 Отменено пользователем")
118
+ except Exception as e:
119
+ print(f"\n❌ Ошибка: {e}")
120
+
121
+
122
+ if __name__ == "__main__":
123
+ main()