### 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