### Full MandreLib Plugin Example with Commands and Scheduler Source: https://manderelib.vercel.app/guide/quick-start.html A comprehensive MandreLib plugin example combining persistent storage, a '.hello' command with UI interaction, a '.stats' command to display plugin usage, and a scheduled task to increment a counter. It includes plugin load/unload logic and requires 'base_plugin', 'mandre_lib', 'mandre_lib.MandreUI', 'mandre_lib.MandreData', and 'ui.bulletin'. ```python __id__ = "my_first_plugin" __name__ = "Мой первый плагин" __version__ = "1.0" __author__ = "@yourname" __description__ = "Плагин с командами и планировщиком" __min_version__ = "11.9.0" from base_plugin import BasePlugin, HookResult from mandre_lib import Mandre, MandreUI, MandreData from ui.bulletin import BulletinHelper class MyFirstPlugin(BasePlugin): def on_plugin_load(self): # Инициализация Mandre.use_persistent_storage(self) self.add_on_send_message_hook() # Команды Mandre.register_command(self, "hello", self.cmd_hello) Mandre.register_command(self, "stats", self.cmd_stats) # Планировщик Mandre.schedule_task(self, "counter", 60, self.increment_counter) self.log("Плагин загружен!") def on_send_message_hook(self, params): return Mandre.handle_outgoing_command(params) or HookResult() def cmd_hello(self, plugin, args, params): """Команда .hello""" MandreUI.show( title="Привет!", items=["Показать статистику", "Очистить данные"], on_select=self.handle_menu_select ) return None def cmd_stats(self, plugin, args, params): """Команда .stats - показывает статистику""" counter = self.get_setting("counter", 0) loads = self.get_setting("load_count", 0) stats = f"📊 Статистика:\n" stats += f"Загрузок: {loads}\n" stats += f"Счётчик: {counter}" BulletinHelper.show_info(stats) return None def handle_menu_select(self, index, text): if index == 0: self.cmd_stats(None, "", {}) elif index == 1: self.set_setting("counter", 0) BulletinHelper.show_success("Данные очищены") def increment_counter(self): """Увеличивает счётчик каждую минуту""" counter = self.get_setting("counter", 0) self.set_setting("counter", counter + 1) def on_plugin_unload(self): Mandre.cancel_task(self, "counter") self.log("Плагин выгружен") ``` -------------------------------- ### Example of Requesting Authentication (Python) Source: https://manderelib.vercel.app/api/mandre-auth.html A practical Python example illustrating the usage of MandreAuth.request(). It defines success and failure callback functions that display messages using BulletinHelper and perform actions accordingly. The example also shows how to set the title and description for the authentication prompt. ```python def request_auth(self): def on_success(): BulletinHelper.show_success("✅ Доступ разрешён") self.perform_action() def on_failure(): BulletinHelper.show_error("❌ Доступ запрещён") MandreAuth.request( on_success=on_success, on_failure=on_failure, title="Требуется подтверждение", description="Подтвердите свою личность" ) ``` -------------------------------- ### Example: Export Settings to JSON and Share Source: https://manderelib.vercel.app/api/mandre-share.html This example demonstrates exporting plugin settings to a JSON file and then sharing that file using `share_file`. It uses `tempfile` to create a temporary file and `json` to serialize the settings. ```python def export_settings(self): import json import tempfile import time settings = { "version": self.version, "settings": {k: v for k, v in self.settings.items()}, "exported_at": time.strftime("%Y-%m-%d %H:%M:%S") } with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as f: json.dump(settings, f, ensure_ascii=False, indent=2) temp_path = f.name Mandre.Share.share_file(temp_path, f"Настройки {self.name}") BulletinHelper.show_success("Настройки экспортированы!") ``` -------------------------------- ### Example: Share Document File Source: https://manderelib.vercel.app/api/mandre-share.html An example demonstrating how to use the `share_file` method to share a PDF document, specifying the file path, dialog title, and MIME type. ```python Mandre.Share.share_file( file_path="/path/to/document.pdf", title="Поделиться документом", mime_type="application/pdf" ) ``` -------------------------------- ### Example: Generate and Share HTML Report Source: https://manderelib.vercel.app/api/mandre-share.html This example shows how to generate an HTML report as a string, save it to a temporary file, and then share it using the `share_file` method. It utilizes `tempfile` for temporary file creation. ```python def generate_report(self): import tempfile html = f""" Отчёт

📊 Отчёт плагина

Плагин: {self.name}

Версия: {self.version}

""" with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False, encoding='utf-8') as f: f.write(html) temp_path = f.name Mandre.Share.share_file(temp_path, "Отчёт") ``` -------------------------------- ### Example: Share Plugin Statistics Source: https://manderelib.vercel.app/api/mandre-share.html This example shows how to generate statistics text and share it using the `share_text` method. It retrieves message count and plugin information to format the text. ```python def share_stats(self): count = self.get_setting("message_count", 0) text = f"""📊 Статистика плагина Отправлено сообщений: {count} Плагин: {self.name} Версия: {self.version} """ Mandre.Share.share_text(text, "Статистика") ``` -------------------------------- ### Example: Share Greeting Text Source: https://manderelib.vercel.app/api/mandre-share.html An example demonstrating how to use the `share_text` method to send a greeting message with a specified dialog title. ```python Mandre.Share.share_text( text="Привет! Это сообщение от моего плагина!", title="Поделиться приветствием" ) ``` -------------------------------- ### Advanced Command Examples Source: https://manderelib.vercel.app/guide/commands.html Various implementations of command handlers including simple triggers, argument parsing, state management, and UI integration. ```python def cmd_ping(self, plugin, args, params): """Команда .ping - проверка работы плагина""" BulletinHelper.show_success("Pong! 🏓") return HookResult(strategy=HookStrategy.CANCEL) def cmd_say(self, plugin, args, params): """Команда .say <текст> - озвучить текст""" if not args: BulletinHelper.show_error("Использование: .say <текст>") return HookResult(strategy=HookStrategy.CANCEL) MandreTTS.speak(args) BulletinHelper.show_success("Озвучиваю...") return HookResult(strategy=HookStrategy.CANCEL) def cmd_stats(self, plugin, args, params): """Команда .stats - показать статистику""" count = self.get_setting("message_count", 0) commands = self.get_setting("command_count", 0) self.set_setting("command_count", commands + 1) stats = f"📊 Статистика:\nСообщений: {count}\nКоманд: {commands + 1}" params["message"] = stats return HookResult(strategy=HookStrategy.MODIFY, params=params) def cmd_menu(self, plugin, args, params): """Команда .menu - показать меню""" MandreUI.show( title="Меню команд", items=["📊 Статистика", "🗑️ Очистить данные", "⚙️ Настройки"], on_select=lambda i, t: self.handle_menu(i) ) return HookResult(strategy=HookStrategy.CANCEL) def cmd_remind(self, plugin, args, params): """Команда .remind <минуты> <текст> - напоминание""" if not args: BulletinHelper.show_error("Использование: .remind <минуты> <текст>") return HookResult(strategy=HookStrategy.CANCEL) parts = args.split(maxsplit=1) if len(parts) < 2: BulletinHelper.show_error("Укажите время и текст") return HookResult(strategy=HookStrategy.CANCEL) try: minutes = int(parts[0]) text = parts[1] self.schedule_reminder(minutes, text) BulletinHelper.show_success(f"Напомню через {minutes} мин") except ValueError: BulletinHelper.show_error("Неверный формат времени") return HookResult(strategy=HookStrategy.CANCEL) ``` -------------------------------- ### Command Notification Example (Python) Source: https://manderelib.vercel.app/api/mandre-notification.html Provides an example of a command handler that triggers notifications based on arguments. It can show a simple notification if no arguments are provided or a dialog notification with custom content. ```python def cmd_notify(self, plugin, args, params): """Показать уведомление""" if not args: Mandre.Notification.show_simple("Тест", "Простое уведомление! 🚀") else: Mandre.Notification.show_dialog( "Demo Plugin", args, "https://i.postimg.cc/436ngppG/image.png" ) return HookResult(strategy=HookStrategy.CANCEL) ``` -------------------------------- ### Importing MandreLib Modules Source: https://manderelib.vercel.app/guide/integration.html Demonstrates the necessary imports to access MandreLib functionality and the base plugin class. ```python from mandre_lib import Mandre, MandreData, MandreUI, MandreTTS, MandreAuth from base_plugin import BasePlugin ``` -------------------------------- ### Full Plugin Lifecycle Implementation Source: https://manderelib.vercel.app/api/mandre.html A comprehensive example demonstrating plugin initialization, storage usage, localization, command registration, task scheduling, and deep link handling using the Mandre library. ```python from mandre_lib import Mandre from base_plugin import BasePlugin, HookResult _translations = { "hello": "Привет, {name}!", "goodbye": "До свидания!" } class MyPlugin(BasePlugin): def on_plugin_load(self): # Активация хранилища Mandre.use_persistent_storage(self) # Регистрация переводов Mandre.register_localizations(self, "ru", _translations) # Регистрация команд self.add_on_send_message_hook() Mandre.register_command(self, "hello", self.cmd_hello) # Планирование задачи Mandre.schedule_task(self, "check", 30, self.periodic_check) # Deep link Mandre.add_tg_alias("my_plugin/action", self.handle_link) Mandre.register_settings_alias(self) def on_send_message_hook(self, params): return Mandre.handle_outgoing_command(params) or HookResult() def cmd_hello(self, plugin, args, params): name = args if args else "друг" greeting = Mandre.t(self, "hello", name=name) params["message"] = greeting return HookResult(strategy=HookStrategy.MODIFY, params=params) def periodic_check(self): self.log("Проверка выполнена") def handle_link(self, intent): uri = str(intent.getData()) self.log(f"Deep link: {uri}") def on_plugin_unload(self): Mandre.cancel_task(self, "check") Mandre.remove_tg_alias("my_plugin/action") ``` -------------------------------- ### Full Plugin Template Source: https://manderelib.vercel.app/guide/integration.html A complete boilerplate for a MandreLib plugin, including lifecycle hooks, command registration, task scheduling, and UI settings creation. ```python __id__ = "my_plugin" __name__ = "Название плагина" __version__ = "1.0.0" __author__ = "@yourname" __description__ = "Описание плагина" __min_version__ = "11.9.0" from base_plugin import BasePlugin, HookResult, HookStrategy from ui.settings import Header, Text, Switch, Divider from ui.bulletin import BulletinHelper from mandre_lib import Mandre, MandreData, MandreUI class MyPlugin(BasePlugin): def on_plugin_load(self): """Вызывается при загрузке плагина""" # Активируем MandreLib Mandre.use_persistent_storage(self) # Добавляем хуки если нужны self.add_on_send_message_hook() # Регистрируем команды Mandre.register_command(self, "mycommand", self.cmd_mycommand) # Запускаем задачи Mandre.schedule_task(self, "task_name", 60, self.periodic_task) self.log("Плагин загружен") def on_send_message_hook(self, params): """Обработка исходящих сообщений""" # Обрабатываем команды result = Mandre.handle_outgoing_command(params) if result: return result # Ваша дополнительная логика return HookResult() def cmd_mycommand(self, plugin, args, params): """Обработчик команды .mycommand""" BulletinHelper.show_info("Команда выполнена!") return None def periodic_task(self): """Периодическая задача""" self.log("Задача выполнена") def create_settings(self): """Создание UI настроек плагина""" return [ Header(text="Настройки плагина"), Switch( text="Включить функцию", description="Описание функции", value=self.get_setting("feature_enabled", False), on_change=lambda v: self.set_setting("feature_enabled", v) ), Divider(), Text( text="О плагине", icon="msg_info", on_click=lambda _: BulletinHelper.show_info("Информация о плагине") ) ] def on_plugin_unload(self): """Вызывается при выгрузке плагина""" # Отменяем все задачи Mandre.cancel_task(self, "task_name") self.log("Плагин выгружен") ``` -------------------------------- ### Organize Keys with Prefixes in Python Source: https://manderelib.vercel.app/guide/sql-kv.html Shows how to use prefixes for organizing keys in SQL KV storage. This example demonstrates setting user-specific data with a common prefix, improving data management and retrieval. ```python Mandre.sql_kv_set(self.id, "user:123:name", "Alice", "kv") Mandre.sql_kv_set(self.id, "user:123:email", "alice@example.com", "kv") ``` -------------------------------- ### Progress Notification Example (Python) Source: https://manderelib.vercel.app/api/mandre-notification.html This example demonstrates how to provide progress updates using simple notifications during a long-running process. It sends periodic notifications indicating the completion percentage and a final dialog notification upon completion. ```python def process_with_notifications(self, items): total = len(items) for i, item in enumerate(items): process_item(item) if (i + 1) % (total // 10) == 0: progress = int((i + 1) / total * 100) Mandre.Notification.show_simple( "Обработка", f"Выполнено {progress}% ({i + 1}/{total})" ) Mandre.Notification.show_dialog( "Обработка завершена", f"Обработано {total} элементов! ✅", "https://i.postimg.cc/436ngppG/image.png" ) ``` -------------------------------- ### Reminder Notification Example (Python) Source: https://manderelib.vercel.app/api/mandre-notification.html This example illustrates setting up a timed reminder using a dialog-style notification. It schedules a task to display a reminder message after a specified delay, featuring a sender name and avatar. ```python def set_reminder(self, text, delay_seconds): import time def send_reminder(): Mandre.Notification.show_dialog( sender_name="Напоминание", message=text, avatar_url="https://i.postimg.cc/436ngppG/image.png" ) task_name = f"reminder_{int(time.time())}" def one_time_task(): send_reminder() Mandre.cancel_task(self, task_name) Mandre.schedule_task(self, task_name, delay_seconds, one_time_task) ``` -------------------------------- ### Activating Persistent Storage Source: https://manderelib.vercel.app/guide/integration.html Shows how to enable automatic data persistence within a plugin's load method, allowing settings to be saved and restored automatically. ```python class MyPlugin(BasePlugin): def on_plugin_load(self): # Активируем персистентное хранилище Mandre.use_persistent_storage(self) self.log("Плагин загружен, MandreLib активирована") ``` -------------------------------- ### Implement a Basic MandreLib Plugin Source: https://manderelib.vercel.app/api/overview.html Demonstrates the structure of a plugin using MandreLib, including initialization, command registration, task scheduling, and hook handling. This example shows how to integrate with the plugin lifecycle and use UI and notification modules. ```python from mandre_lib import Mandre, MandreData, MandreUI from base_plugin import BasePlugin, HookResult, HookStrategy class MyPlugin(BasePlugin): def on_plugin_load(self): # Активация хранилища Mandre.use_persistent_storage(self) self.add_on_send_message_hook() # Регистрация команд Mandre.register_command(self, "hello", self.cmd_hello) Mandre.register_command(self, "device", self.cmd_device) Mandre.register_command(self, "notify", self.cmd_notify) # Планирование задачи Mandre.schedule_task(self, "task", 60, self.periodic_task) def on_send_message_hook(self, params): return Mandre.handle_outgoing_command(params) or HookResult() def cmd_hello(self, plugin, args, params): MandreUI.show( title="Привет!", items=["Вариант 1", "Вариант 2"], on_select=lambda i, t: self.log(f"Выбрано: {t}") ) return HookResult(strategy=HookStrategy.CANCEL) def cmd_device(self, plugin, args, params): # Новое в 1.6.3: информация об устройстве info = Mandre.Device.get_simple_info() params["message"] = f"📱 {info}" return HookResult(strategy=HookStrategy.MODIFY, params=params) def cmd_notify(self, plugin, args, params): # Новое в 1.6.3: системные уведомления Mandre.Notification.show_simple("Плагин", args or "Тест!") return HookResult(strategy=HookStrategy.CANCEL) def periodic_task(self): self.log("Задача выполнена") def on_plugin_unload(self): Mandre.cancel_task(self, "task") ``` -------------------------------- ### Implement common task patterns in MandreLib Source: https://manderelib.vercel.app/guide/scheduler.html Provides various practical examples of using the task scheduler, including auto-saving data, periodic updates, cache cleanup, dynamic reminders, and system monitoring. ```python # Автосохранение def auto_save(self): data = self.collect_data() MandreData.write_persistent_json(self.id, "backup.json", data) # Периодическая проверка с UI обновлением def check_for_updates(self): if self.fetch_updates(): run_on_ui_thread(lambda: BulletinHelper.show_info("Доступны обновления!")) # Очистка кэша def cleanup_cache(self): cache = MandreData.read_persistent_json(self.id, "cache.json", {}) # ... логика фильтрации ... MandreData.write_persistent_json(self.id, "cache.json", cleaned_cache) # Динамическое напоминание def schedule_reminder(self, minutes, text): task_name = f"reminder_{int(time.time())}" Mandre.schedule_task(self, task_name=task_name, interval_seconds=minutes * 60, callback=remind) # Мониторинг состояния def monitor_state(self): memory_usage = self.get_memory_usage() if memory_usage > 100: self.log(f"⚠️ Высокое использование памяти: {memory_usage}MB") ``` -------------------------------- ### Validate Command Arguments in Python Source: https://manderelib.vercel.app/guide/commands.html Illustrates best practices for validating command arguments in Python before processing them. The example checks for the presence and correct format of arguments, providing user-friendly error messages if validation fails. ```python def cmd_set(self, plugin, args, params): if not args: BulletinHelper.show_error("Использование: .set <ключ> <значение>") return HookResult(strategy=HookStrategy.CANCEL) parts = args.split(maxsplit=1) if len(parts) < 2: BulletinHelper.show_error("Укажите ключ и значение") return HookResult(strategy=HookStrategy.CANCEL) key, value = parts self.set_setting(key, value) ``` -------------------------------- ### Localize Plugin Commands and UI Elements Source: https://manderelib.vercel.app/guide/localization.html Provides examples of integrating localization into command handlers and UI component definitions. This ensures that all user-facing text remains consistent and localized. ```python _translations = { "cmd_help_desc": "Показать справку по командам", "help_text": "📖 Доступные команды:\n.help - {help_desc}", "settings_header": "Настройки плагина", "version": "Версия: {version}" } def cmd_help(self, plugin, args, params): help_text = Mandre.t(self, "help_text", help_desc=Mandre.t(self, "cmd_help_desc")) params["message"] = help_text return HookResult(strategy=HookStrategy.MODIFY, params=params) def create_settings(self): return [ Header(text=Mandre.t(self, "settings_header")), Text(text=Mandre.t(self, "version", version="1.0")) ] ``` -------------------------------- ### Create Basic MandreLib Plugin Source: https://manderelib.vercel.app/guide/quick-start.html This Python snippet demonstrates the creation of a minimal MandreLib plugin. It initializes persistent storage, increments a load counter, and logs the plugin's load count. It requires the 'base_plugin', 'mandre_lib', and 'ui.bulletin' modules. ```python __id__ = "my_first_plugin" __name__ = "Мой первый плагин" __version__ = "1.0" __author__ = "@yourname" __description__ = "Простой плагин с MandreLib" __min_version__ = "11.9.0" from base_plugin import BasePlugin from mandre_lib import Mandre from ui.bulletin import BulletinHelper class MyFirstPlugin(BasePlugin): def on_plugin_load(self): # Активируем персистентное хранилище Mandre.use_persistent_storage(self) # Увеличиваем счётчик загрузок count = self.get_setting("load_count", 0) self.set_setting("load_count", count + 1) self.log(f"Плагин загружен {count + 1} раз!") BulletinHelper.show_success("Плагин загружен!") ``` -------------------------------- ### Add Command to MandreLib Plugin Source: https://manderelib.vercel.app/guide/quick-start.html Extends a MandreLib plugin by adding a new command, '.hello'. This command displays a UI prompt with selectable options. It utilizes 'base_plugin', 'mandre_lib', and 'mandre_lib.MandreUI' for command registration and UI interaction. The hook ensures command handling. ```python from base_plugin import BasePlugin, HookResult from mandre_lib import Mandre, MandreUI class MyFirstPlugin(BasePlugin): def on_plugin_load(self): Mandre.use_persistent_storage(self) self.add_on_send_message_hook() # Регистрируем команду Mandre.register_command(self, "hello", self.cmd_hello) def on_send_message_hook(self, params): # Обрабатываем команды return Mandre.handle_outgoing_command(params) or HookResult() def cmd_hello(self, plugin, args, params): """Команда .hello - показывает приветствие""" MandreUI.show( title="Привет!", items=["Вариант 1", "Вариант 2", "Вариант 3"], on_select=lambda i, t: self.log(f"Выбрано: {t}"), message="Выберите один из вариантов" ) return None # Сообщение не отправится ``` -------------------------------- ### Task Completion Notification Example (Python) Source: https://manderelib.vercel.app/api/mandre-notification.html An example demonstrating how to send a simple notification upon successful completion of a task. This is useful for providing feedback to the user that a background operation has finished. ```python def on_task_complete(self): Mandre.Notification.show_simple( title="Задача выполнена", text="Обработка данных завершена успешно! ✅" ) ``` -------------------------------- ### Add Docstrings for Command Documentation in Python Source: https://manderelib.vercel.app/guide/commands.html Emphasizes the importance of adding docstrings to Python command functions for documentation. The example shows how to include a brief description, usage, and examples within the docstring. ```python def cmd_example(self, plugin, args, params): """Команда .example - описание команды Примеры: .example test 123 .example "hello world" 456 """ pass ``` -------------------------------- ### Python: Initialize MandreLib Plugin and Register Command Source: https://manderelib.vercel.app/examples/calculator.html This Python snippet demonstrates the initialization phase of a MandreLib plugin. It shows how to enable persistent storage, add a message sending hook, register a custom command ('.calc'), and schedule a recurring task for auto-saving history. ```python def on_plugin_load(self): # Активируем персистентное хранилище Mandre.use_persistent_storage(self) self.add_on_send_message_hook() # Регистрируем команду .calc Mandre.register_command(self, "calc", self.cmd_calc) # Автосохранение каждую минуту Mandre.schedule_task(self, "save_history", 60, self.save_history) ``` -------------------------------- ### Mandre.sql_init_kv Source: https://manderelib.vercel.app/guide/sql-kv.html Initializes a new key-value storage table for a specific plugin. ```APIDOC ## [METHOD] Mandre.sql_init_kv ### Description Creates a dedicated table for storing key-value pairs if it does not already exist. ### Parameters - **plugin_id** (string) - Required - The unique ID of the plugin. - **table_name** (string) - Optional - The name of the table (default: "mandre_kv"). ### Request Example ```python Mandre.sql_init_kv(self.id, "my_plugin_kv") ``` ``` -------------------------------- ### Manage Plugin Settings Source: https://manderelib.vercel.app/api/mandre-data.html Demonstrates simple read and write operations to manage plugin configuration settings. ```python def save_settings(self): settings = { "enabled": True, "interval": 60, "notifications": True } MandreData.write_persistent_json(self.id, "settings.json", settings) def load_settings(self): settings = MandreData.read_persistent_json( self.id, "settings.json", {"enabled": False, "interval": 30} ) self.enabled = settings.get("enabled", False) self.interval = settings.get("interval", 30) ``` -------------------------------- ### Complete Deep Link Plugin Example in Python Source: https://manderelib.vercel.app/guide/deep-linking.html A comprehensive example of a Mandre Lib plugin that utilizes deep linking. It registers aliases for opening items and performing actions, handles different commands, and includes settings management. ```python __id__ = "deeplink_plugin" __name__ = "Deep Link Плагин" __version__ = "1.0" __author__ = "@yourname" __description__ = "Плагин с deep linking" __min_version__ = "11.9.0" from base_plugin import BasePlugin from mandre_lib import Mandre, MandreData from ui.bulletin import BulletinHelper from ui.settings import Header, Text import urllib.parse class DeepLinkPlugin(BasePlugin): def on_plugin_load(self): Mandre.use_persistent_storage(self) # Регистрируем алиасы Mandre.add_tg_alias("deeplink_plugin/open", self.handle_open) Mandre.add_tg_alias("deeplink_plugin/action", self.handle_action) Mandre.register_settings_alias(self) def handle_open(self, intent): """Обработчик tg://deeplink_plugin/open?id=123""" try: uri_str = str(intent.getData()) if "id=" in uri_str: item_id = uri_str.split("id=")[1].split("&")[0] self.open_item(item_id) BulletinHelper.show_success(f"Открыт элемент {item_id}") else: BulletinHelper.show_error("ID не указан") except Exception as e: self.log(f"Ошибка: {e}") BulletinHelper.show_error("Ошибка обработки ссылки") def handle_action(self, intent): """Обработчик tg://deeplink_plugin/action?cmd=stats""" try: uri_str = str(intent.getData()) if "cmd=" in uri_str: command = uri_str.split("cmd=")[1].split("&")[0] if command == "stats": self.show_statistics() elif command == "clear": self.clear_data() else: BulletinHelper.show_error(f"Неизвестная команда: {command}") except Exception as e: self.log(f"Ошибка: {e}") def create_settings(self): return [ Header(text="Deep Links"), Text( text="Открыть настройки", description=f"tg://settings/{self.id}", icon="msg_settings", on_click=lambda _: self.copy_link(f"tg://settings/{self.id}") ), Text( text="Показать статистику", description="tg://deeplink_plugin/action?cmd=stats", icon="msg_stats", on_click=lambda _: self.copy_link("tg://deeplink_plugin/action?cmd=stats") ) ] def copy_link(self, link): """Копировать ссылку в буфер""" # Реализация копирования BulletinHelper.show_success("Ссылка скопирована") def on_plugin_unload(self): # Удаляем алиасы Mandre.remove_tg_alias("deeplink_plugin/open") Mandre.remove_tg_alias("deeplink_plugin/action") ``` -------------------------------- ### Track Plugin State in Python Source: https://manderelib.vercel.app/guide/sql-kv.html Illustrates how to track the state of a plugin using Mandre's SQL KV. It includes functions to initialize the state, start and stop tasks, and retrieve the current status, storing state information as key-value pairs. ```python def on_plugin_load(self): Mandre.use_persistent_storage(self) Mandre.sql_init_kv(self.id, "state_kv") # Инициализировать состояние state = Mandre.sql_kv_get(self.id, "plugin_state", "state_kv") if not state: Mandre.sql_kv_set(self.id, "plugin_state", "idle", "state_kv") def start_task(self): """Запустить задачу""" Mandre.sql_kv_set(self.id, "plugin_state", "running", "state_kv") Mandre.sql_kv_set(self.id, "task_start_time", int(time.time()), "state_kv") self.log("Задача запущена") def stop_task(self): """Остановить задачу""" Mandre.sql_kv_set(self.id, "plugin_state", "idle", "state_kv") start_time = Mandre.sql_kv_get_int(self.id, "task_start_time", 0, "state_kv") duration = int(time.time()) - start_time self.log(f"Задача завершена. Длительность: {duration} сек") def get_status(self): """Получить статус""" state = Mandre.sql_kv_get(self.id, "plugin_state", "state_kv") or "unknown" return state ``` -------------------------------- ### Python Best Practice: Use Meaningful Filenames Source: https://manderelib.vercel.app/api/mandre-data.html This Python code snippet highlights the best practice of using descriptive filenames when interacting with `MandreData.write_persistent_json`. It contrasts good examples with meaningful names against poor examples using generic names like 'data.json' or 'file1.json'. ```python # ✅ Хорошо MandreData.write_persistent_json(self.id, "user_database.json", data) MandreData.write_persistent_json(self.id, "settings.json", settings) # ❌ Плохо MandreData.write_persistent_json(self.id, "data.json", data) MandreData.write_persistent_json(self.id, "file1.json", settings) ``` -------------------------------- ### Mandre.sql_kv_delete_prefix Source: https://manderelib.vercel.app/guide/sql-kv.html Removes all keys starting with a specific prefix. ```APIDOC ## [METHOD] Mandre.sql_kv_delete_prefix ### Description Bulk deletes keys that match the provided prefix string. ### Parameters - **plugin_id** (string) - Required - **prefix** (string) - Required - **table_name** (string) - Optional ``` -------------------------------- ### Implement User Database Source: https://manderelib.vercel.app/api/mandre-data.html Example of managing a user database within a JSON file, including adding, retrieving, and removing user records. ```python def add_user(self, user_id, username): db = MandreData.read_persistent_json(self.id, "users.json", {"users": []}) for user in db["users"]: if user["id"] == user_id: return False db["users"].append({"id": user_id, "username": username, "added_at": time.time()}) MandreData.write_persistent_json(self.id, "users.json", db) return True ``` -------------------------------- ### Registering Commands in MandreLib Source: https://manderelib.vercel.app/guide/commands.html Demonstrates how to initialize a plugin, register commands, and hook into the message processing pipeline using MandreLib's core classes. ```python from mandre_lib import Mandre from base_plugin import BasePlugin, HookResult class MyPlugin(BasePlugin): def on_plugin_load(self): Mandre.use_persistent_storage(self) self.add_on_send_message_hook() # Регистрируем команды Mandre.register_command(self, "hello", self.cmd_hello) Mandre.register_command(self, "echo", self.cmd_echo) def on_send_message_hook(self, params): # MandreLib автоматически обработает команды result = Mandre.handle_outgoing_command(params) if result: return result # Ваша дополнительная логика return HookResult() ``` -------------------------------- ### Implement TTS Command Hooks Source: https://manderelib.vercel.app/api/mandre-tts.html Examples of integrating MandreTTS into command handlers, including simple text-to-speech, time announcement, and notification reading. ```python def cmd_say(self, plugin, args, params): if not args: BulletinHelper.show_error("Использование: .say <текст>") return HookResult(strategy=HookStrategy.CANCEL) MandreTTS.speak(args) return HookResult(strategy=HookStrategy.CANCEL) def cmd_time(self, plugin, args, params): time_str = datetime.now().strftime("%H:%M") MandreTTS.speak(f"Сейчас {time_str}") return HookResult(strategy=HookStrategy.CANCEL) def on_new_message(self, message): if self.get_setting("tts_enabled", False): sender = message.get("sender_name", "Неизвестный") text = message.get("text", "") if text: MandreTTS.speak(f"Сообщение от {sender}: {text}") ``` -------------------------------- ### Import Mandre Library Source: https://manderelib.vercel.app/api/mandre-share.html This snippet shows how to import the Mandre library for use in your Python project. Ensure the Mandre library is installed in your environment. ```python from mandre_lib import Mandre ``` -------------------------------- ### Register Multiple Commands in Python Source: https://manderelib.vercel.app/guide/commands.html Demonstrates how to register multiple commands simultaneously using a dictionary in Python. This approach simplifies the command registration process by iterating over a predefined command-handler mapping. ```python def on_plugin_load(self): Mandre.use_persistent_storage(self) self.add_on_send_message_hook() # Регистрируем несколько команд commands = { "help": self.cmd_help, "start": self.cmd_start, "stop": self.cmd_stop, "status": self.cmd_status, "config": self.cmd_config } for cmd, handler in commands.items(): Mandre.register_command(self, cmd, handler) def cmd_help(self, plugin, args, params): """Показать справку по командам""" help_text = """ 📖 Доступные команды: .help - эта справка .start - запустить функцию .stop - остановить функцию .status - показать статус .config - настройки """.strip() params["message"] = help_text return HookResult(strategy=HookStrategy.MODIFY, params=params) ``` -------------------------------- ### Check Notification Settings Before Sending in Python Source: https://manderelib.vercel.app/guide/notifications.html Provides an example of checking user notification preferences before sending a notification. This prevents sending alerts when they are disabled by the user. ```python if self.get_setting("notifications_enabled", True): Mandre.Notification.show_simple("Title", "Text") ``` -------------------------------- ### Create Full TTS Plugin Source: https://manderelib.vercel.app/api/mandre-tts.html A complete example of a Mandre plugin implementing TTS functionality, including command registration, message hooks, and settings UI. ```python __id__ = "tts_plugin" __name__ = "TTS Плагин" __version__ = "1.0" from base_plugin import BasePlugin, HookResult, HookStrategy from mandre_lib import Mandre, MandreTTS, MandreUI from ui.bulletin import BulletinHelper from ui.settings import Header, Switch, Text class TTSPlugin(BasePlugin): def on_plugin_load(self): Mandre.use_persistent_storage(self) self.add_on_send_message_hook() Mandre.register_command(self, "say", self.cmd_say) Mandre.register_command(self, "time", self.cmd_time) def on_send_message_hook(self, params): return Mandre.handle_outgoing_command(params) or HookResult() def cmd_say(self, plugin, args, params): if not args: BulletinHelper.show_error("Использование: .say <текст>") return HookResult(strategy=HookStrategy.CANCEL) MandreTTS.speak(args) BulletinHelper.show_success("🔊 Озвучиваю...") return HookResult(strategy=HookStrategy.CANCEL) def cmd_time(self, plugin, args, params): from datetime import datetime now = datetime.now() time_str = now.strftime("%H:%M") MandreTTS.speak(f"Сейчас {time_str}") BulletinHelper.show_info(f"🕐 {time_str}") return HookResult(strategy=HookStrategy.CANCEL) def create_settings(self): return [ Header(text="TTS"), Text( text="Тест озвучивания", icon="msg_voicechat", on_click=lambda _: MandreTTS.speak("Тестовое сообщение") ) ] ``` -------------------------------- ### Build Settings Interface Source: https://manderelib.vercel.app/guide/ui.html Demonstrates constructing a settings page using MandreUI components like Headers, Switches, and Text inputs. It shows how to handle navigation between different settings tabs. ```python from ui.settings import Header, Text, Switch, Divider, Input def create_settings(self): tab = self.get_setting("current_tab", 0) if tab == 0: # Основные return [ Header(text="Основные настройки"), Switch( text="Включить функцию", value=self.get_setting("enabled", True), on_change=lambda v: self.set_setting("enabled", v) ), Text( text="Выбрать чат", icon="msg_select", on_click=lambda _: MandreUI.select_chat( title="Выбор чата", on_select=self.save_chat ) ) ] elif tab == 1: # Данные return [ Header(text="Управление данными"), Text( text="Экспортировать", icon="msg_shareout", on_click=lambda _: self.export_data() ), Text( text="Импортировать", icon="msg_input", on_click=lambda _: self.import_data() ), Divider(), Text( text="Очистить всё", icon="msg_delete", red=True, on_click=lambda _: self.confirm_delete() ) ] ``` -------------------------------- ### Initialize Plugin and Register Commands with MandreLib Source: https://manderelib.vercel.app/ This snippet demonstrates how to initialize a plugin using MandreLib, enable persistent storage, and register interactive commands. It utilizes the Mandre and MandreUI classes to handle plugin lifecycle events and user interface interactions. ```python from mandre_lib import Mandre, MandreData, MandreUI from base_plugin import BasePlugin class MyPlugin(BasePlugin): def on_plugin_load(self): # Активируем персистентное хранилище Mandre.use_persistent_storage(self) # Регистрируем команды Mandre.register_command(self, "hello", self.cmd_hello) Mandre.register_command(self, "device", self.cmd_device) self.log("Плагин загружен!") def cmd_hello(self, plugin, args, params): MandreUI.show( title="Привет!", items=["Вариант 1", "Вариант 2"], on_select=lambda i, t: self.log(f"Выбрано: {t}") ) return None def cmd_device(self, plugin, args, params): # Показываем информацию об устройстве info = Mandre.Device.get_simple_info() params["message"] = f"📱 {info}" return HookResult(strategy=HookStrategy.MODIFY, params=params) ``` -------------------------------- ### Best Practices for Mandre Development Source: https://manderelib.vercel.app/guide/device.html Recommended patterns for error handling, data caching, and choosing the appropriate API methods to ensure application stability and performance. ```python # Error Handling info = Mandre.Device.get_device_info() if "error" in info: return # Caching if need_update(): info = Mandre.Device.get_device_info() cache_info(info) # Efficient API Usage simple = Mandre.Device.get_simple_info() BulletinHelper.show_info(simple) ``` -------------------------------- ### Structure Translations by Category in Python Source: https://manderelib.vercel.app/guide/localization.html Provides an example of how to organize translation strings into logical categories within a Python dictionary. This improves maintainability and readability of the translation files. ```python _translations = { # Команды "cmd_help": "Справка", "cmd_stats": "Статистика", "cmd_clear": "Очистить", # Настройки "settings_header": "Настройки", "settings_enable": "Включить", "settings_disable": "Выключить", # Уведомления "notify_success": "Успешно!", "notify_error": "Ошибка!", "notify_warning": "Внимание!", # Диалоги "dialog_confirm": "Подтвердить", "dialog_cancel": "Отмена", # Ошибки "error_network": "Ошибка сети", "error_permission": "Нет доступа", "error_invalid": "Неверные данные" } ```