### CactusLib: Plugin Database Management
Source: https://cactus.den4iksop.org/dev/plugin_class
Demonstrates how to use the built-in JSON database for plugins in CactusLib. It shows methods for getting, setting, popping, and clearing data, along with an example of a command usage counter.
```python
class MyPlugin(CactusUtils.Plugin):
@command(doc="Увеличивает и показывает счетчик")
def count(self, cmd: CactusUtils.Command):
# Получаем текущее значение, если его нет, то 0
current_count = self.get("usage_count", 0)
current_count += 1
# Сохраняем новое значение
self.set("usage_count", current_count)
cmd.answer(f"Эту команду использовали {current_count} раз.")
return HookResult(strategy=HookStrategy.CANCEL)
```
--------------------------------
### CactusLib: Send Message with Inline Keyboard
Source: https://cactus.den4iksop.org/dev/inline_keyboards
Demonstrates sending a message with an inline keyboard attached. The `markup` object is passed directly to the `cmd.answer` method. Includes examples of creating buttons with URLs and callbacks. Dependencies: `CactusUtils.Inline.Markup`, `CactusUtils.Inline.Button`, `CactusUtils.Inline.CallbackData`, `CactusUtils.Command`, `HookResult`, `HookStrategy`.
```python
def send_menu(self, cmd: CactusUtils.Command):
# Создаем данные для колбэка.
# Формат: "cactus://{plugin_id}/{method}?{key}={value}"
cb_data = CactusUtils.Inline.CallbackData(self.id, "menu_press", item="A")
markup = CactusUtils.Inline.Markup().add_row(
CactusUtils.Inline.Button("Открыть Google", url="https://google.com/"),
CactusUtils.Inline.Button("Нажми меня!", callback_data=cb_data)
)
cmd.answer("Выберите опцию:", markup=markup)
return HookResult(strategy=HookStrategy.CANCEL)
```
--------------------------------
### Create a command that repeats user arguments in Python
Source: https://cactus.den4iksop.org/dev/commands
This Python example shows how to create an 'echo' command for a Cactus Den bot. The command takes user input as raw arguments and repeats it back in a formatted HTML response. It includes a check for empty arguments and uses `escape_html` to prevent potential injection vulnerabilities.
```python
class MyPlugin(CactusUtils.Plugin):
@command(doc="Повторяет ваши слова")
def echo(self, cmd: CactusUtils.Command):
if not cmd.raw_args:
cmd.answer("Мне нечего повторять.")
return HookResult(strategy=HookStrategy.CANCEL)
# Используем HTML-безопасную версию для избежания инъекций
safe_text = self.utils.escape_html(cmd.raw_args)
cmd.answer(f"Вы сказали: {safe_text}")
return HookResult(strategy=HookStrategy.CANCEL)
```
--------------------------------
### CactusLib: Create Button with Emoji/Icon
Source: https://cactus.den4iksop.org/dev/inline_keyboards
Example of creating an inline button with custom emoji or icon in the button text. Uses a specific syntax for embedding these elements. Dependencies: `CactusUtils.Inline.Button`.
```python
button = CactusUtils.Inline.Button(
# ID премиум эмодзи
text=" Нажми меня",
query="привет exteraGram", # Это будет выставлено в поле сообщения
)
```
```python
button = CactusUtils.Inline.Button(
# ID Drawable иконки
text=" Нажми меня",
query="привет AyuGram", # Это будет выставлено в поле сообщения
)
```
--------------------------------
### CactusLib: Plugin Localization (i18n)
Source: https://cactus.den4iksop.org/dev/plugin_class
Explains how to implement multi-language support within CactusLib plugins using the `strings` dictionary and the `self.string` method. It includes examples for defining strings in multiple languages and retrieving them dynamically.
```python
class MyPlugin(CactusUtils.Plugin):
strings = {
"en": {
"GREETING": "Hello, {}!",
"__doc__": "This is a plugin description."
},
"ru": {
"GREETING": "Привет, {}!",
"__doc__": "Это описание плагина."
}
}
# ...
@command(doc="Персональное приветствие")
def greet(self, cmd: CactusUtils.Command):
if not cmd.args:
cmd.answer("Пожалуйста, укажите имя.")
return HookResult(strategy=HookStrategy.CANCEL)
user_name = cmd.args[0]
# Автоматически выберет "Привет" или "Hello"
greeting_text = self.string("GREETING", user_name)
cmd.answer(greeting_text)
return HookResult(strategy=HookStrategy.CANCEL)
```
--------------------------------
### Get Temporary Directory
Source: https://cactus.den4iksop.org/dev/advanced/utils
Returns a special temporary directory named 'cactuslib_temp_files' within the cache directory. This directory is created if it does not already exist. It returns the absolute path to this temporary directory.
```Python
temp_dir = CactusUtils.FileSystem.tempdir()
print(f"Временный каталог CactusLib: {temp_dir.getAbsolutePath()}")
```
--------------------------------
### Handle message sending events with callbacks in Python
Source: https://cactus.den4iksop.org/dev/commands
This Python example demonstrates how to use the `on_sent` callback in a Cactus Den bot plugin to perform actions after a message is sent. The `_on_sent` method is triggered when the `test` command's answer message is sent. Inside this method, you can edit the message, send a reply, or delete the original message using the provided `params` object.
```python
class MyPlugin(CactusUtils.Plugin):
def _on_sent(self, params: CactusUtils.Inline.CallbackParams):
# Вы можете сделать что угодно с сообщением, которое отправилось
# Вы можете изменить текст
params.edit("Edited message")
# Вы можете отправить сообщение в ответ на исходное
self.utils.send_message(params.message.getDialogId(), "Ответ на исходное сообщение", replyToMsg=params.message)
# Вы можете удалить сообщение
params.delete()
@command()
def test(self, cmd: CactusUtils.Command):
cmd.answer("Ожидайте...", on_sent=lambda params: self._on_sent(params))
return HookResult(strategy=HookStrategy.CANCEL)
```
--------------------------------
### Append Text to User's Formatted Message (Python)
Source: https://cactus.den4iksop.org/dev/parsing
This Python example demonstrates how to take formatted text provided by a user and append additional content to it. The `cmd.html()` method retrieves the user's message along with its formatting. The custom text, also formatted using HTML, is then appended to this retrieved HTML. Finally, the combined HTML string is sent back as a reply using `cmd.answer`.
```python
class MyPlugin(CactusUtils.Plugin):
@command(doc="Добавляет подпись к вашему сообщению")
def append(self, cmd: CactusUtils.Command):
# Получаем текст и entities из "отправляемого" сообщения
html_text = cmd.html()
html_text += "\n\n✍️ Подписано крутым кактусом"
# Просто отправляем измененную строку
cmd.answer(html_text)
return HookResult(strategy=HookStrategy.CANCEL)
```
--------------------------------
### Реализация команды «Hello, World!» Python
Source: https://cactus.den4iksop.org/dev/getting_started
Создает команду «hello» с использованием декоратора `@command`. Метод `hello` отвечает сообщением «Hello, World!» и использует `cmd.answer()` для отправки ответа. Также включает обязательные методы `on_plugin_load` и `on_plugin_unload`.
```python
# ... метаданные и импорты ...
class MyFirstPlugin(CactusUtils.Plugin):
def on_plugin_load(self):
# Обязательно вызывайте родительский метод! Это критически важно.
super().on_plugin_load()
# Этот метод вызывается при загрузке плагина
self.info("Мой первый плагин успешно загружен!")
def on_plugin_unload(self):
# Обязательно вызывайте родительский метод! Это критически важно.
super().on_plugin_unload()
# Этот метод вызывается при выгрузке плагина
self.info("Мой первый плагин успешно выгружен!")
@command(doc="Отправляет приветствие")
def hello(self, cmd: CactusUtils.Command):
# cmd - это объект с информацией о вызванной команде
# cmd.answer() - это удобный метод для ответа в тот же чат
cmd.answer("Hello, World from MyFirstPlugin!")
return HookResult(strategy=HookStrategy.CANCEL)
```
--------------------------------
### Getting Chat Information with get_chat
Source: https://cactus.den4iksop.org/dev/advanced/rpc_calls
Retrieve comprehensive information about a chat using the `get_chat` method. This method requires the chat ID and returns detailed chat data. The example demonstrates accessing the chat title from the response and includes error handling for `TLRPCException`.
```python
try:
result = self.utils.Telegram.get_chat(-10012345678)
chat_title = result.response.chats.get(0).title
self.utils.show_info(f"Информация о чате: {chat_title}")
except self.utils.Telegram.TLRPCException as e:
self.error(f"Не удалось получить информацию о чате: {e.error.text}")
```
--------------------------------
### Define basic command with aliases and description in Python
Source: https://cactus.den4iksop.org/dev/commands
This snippet demonstrates how to create a simple command in a Cactus Den bot plugin. It includes defining string translations for different languages, setting up command aliases, and providing a command description for help messages. The `ping` command sends a 'PONG!' response and can be triggered with `.ping` or `.p`.
```python
class MyPlugin(CactusUtils.Plugin):
strings = {
"en": {
"PING_DOC": "Checks if the plugin is working.",
"pong": "🏓 PONG!",
},
"ru": {
"PING_DOC": "Проверяет, работает ли плагин.",
"pong": "🏓 ПОНГ!",
}
}
@command(aliases=["p"], doc="PING_DOC")
def ping(self, cmd: CactusUtils.Command):
# Используем `answer` для отправки ответа
cmd.answer(self.string("pong"))
return HookResult(strategy=HookStrategy.CANCEL)
def _on_sent_ping(self, params: CactusUtils.Inline.CallbackParams):
# Редактируем сообщение
params.edit(self.string("pong"))
# Удаляем сообщение через 5 секунд
threading.Timer(5, lambda: params.delete()).start()
@command(aliases=["p"], doc="PING_DOC")
def ping2(self, cmd: CactusUtils.Command):
# Используем `on_sent` для редактирования сообщения после отправки
cmd.answer("...", on_sent=lambda params: self._on_sent_ping(params))
return HookResult(strategy=HookStrategy.CANCEL)
```
--------------------------------
### Обработка нажатий на inline-кнопки с @CactusUtils.Inline.on_click
Source: https://cactus.den4iksop.org/dev/inline_keyboards
Декоратор @CactusUtils.Inline.on_click связывает функцию-обработчик с определенным callback_data кнопки. Обработчику передается объект CallbackParams, содержащий информацию о сообщении, UI-элементе и методы для взаимодействия с сообщением (редактирование текста/клавиатуры, удаление).
```python
class MyPlugin(CactusUtils.Plugin):
@command(doc="Показывает интерактивное меню")
def menu(self, cmd: CactusUtils.Command):
markup = CactusUtils.Inline.Markup().add_row(
CactusUtils.Inline.Button(
" Увеличить счетчик",
callback_data=CactusUtils.Inline.CallbackData(self.id, "counter_click")
)
)
count = self.get("menu_counter", 0)
cmd.answer(f"Счетчик: {count}", markup=markup)
return HookResult(strategy=HookStrategy.CANCEL)
@CactusUtils.Inline.on_click("counter_click")
def _on_counter_click(self, params: CactusUtils.Inline.CallbackParams):
count = self.get("menu_counter", 0) + 1
self.set("menu_counter", count)
markup = CactusUtils.Inline.Markup().add_row(
CactusUtils.Inline.Button(
" Увеличить счетчик",
callback_data=CactusUtils.Inline.CallbackData(self.id, "counter_click")
)
)
params.edit(f"Счетчик: {count}", markup=markup)
```
--------------------------------
### Отправка глобальных сообщений с inline-кнопками
Source: https://cactus.den4iksop.org/dev/inline_keyboards
Для отправки сообщений с inline-кнопками, которые будут видны всем пользователям (глобально), необходимо установить параметр is_global=True в конструкторе CactusUtils.Inline.Markup. Это позволяет создавать интерактивные элементы, доступные широкой аудитории.
```python
class MyPlugin(CactusUtils.Plugin):
@command(doc="Показывает интерактивное меню всем пользователям")
def items(self, cmd: CactusUtils.Command):
markup = CactusUtils.Inline.Markup(is_global=True).add_row(
CactusUtils.Inline.Button(
"Нажми меня!",
url="https://t.me/CactusPlugins"
)
)
cmd.answer(f"Сообщение с Inline-кнопками для всех", markup=markup)
return HookResult(strategy=HookStrategy.CANCEL)
@command(doc="Показывает интерактивное меню всем пользователям альтернативным методом")
def items2(self, cmd: CactusUtils.Command):
markup = CactusUtils.Inline.Markup(is_global=True).add_row(
CactusUtils.Inline.Button(
"Нажми меня!",
url="https://t.me/CactusPlugins"
)
)
cmd.answer(f"Сообщение с Inline-кнопками для всех")
return HookResult(strategy=HookStrategy.CANCEL)
```
--------------------------------
### Get Application Cache Directory
Source: https://cactus.den4iksop.org/dev/advanced/utils
Retrieves the application's external cache directory. This function can also create subdirectories within the cache directory. It takes optional path components as string arguments.
```Python
# Получить кэш-каталог
cache_dir = CactusUtils.FileSystem.cachedir()
print(f"Кэш-каталог: {cache_dir.getAbsolutePath()}")
# Получить и создать временный подкаталог кэша
temp_cache_dir = CactusUtils.FileSystem.cachedir("temp_images")
print(f"Временный каталог изображений: {temp_cache_dir.getAbsolutePath()}")
```
--------------------------------
### Deleting Messages with delete_messages
Source: https://cactus.den4iksop.org/dev/advanced/rpc_calls
Remove messages from a chat using the `delete_messages` method. This method requires a list of message IDs and the chat ID. The example demonstrates deleting specific messages from a chat identified by `command.params.peer`.
```python
# Удаляем сообщения с ID 101 и 102 в текущем чате
messages_to_delete = [101, 102]
self.utils.Telegram.delete_messages(messages_to_delete, command.params.peer)
```
--------------------------------
### Отправка файлов с подписью с помощью CactusUtils.Plugin.answer_file
Source: https://cactus.den4iksop.org/dev/advanced/messages
Метод `answer_file` (доступен через `CactusUtils.Plugin`) отправляет файл с возможностью добавления подписи. Принимает параметры команды, путь к файлу и опциональную подпись. По умолчанию парсит подпись как Markdown.
```python
@command("getlogs")
def handle_logs(self, command: CactusUtils.Command):
log_content = "some log data..."
# Записываем контент во временный файл
file_path = self.utils.FileSystem.write_temp_file("logs.txt", log_content.encode("utf-8"), delete_after=60)
self.answer_file(command.params, file_path, caption="Вот ваши логи:")
return HookResult(strategy=HookStrategy.CANCEL)
```
--------------------------------
### CactusLib: Plugin Data Import/Export
Source: https://cactus.den4iksop.org/dev/plugin_class
Details how to handle custom data persistence for CactusLib plugins during import and export operations. It covers implementing `export_data` and `import_data` methods to manage complex data structures beyond the built-in JSON database.
```python
class MyPlugin(CactusUtils.Plugin):
def on_plugin_load(self):
super().on_plugin_load()
self.non_db_data = set() # Данные, которые не хранятся в JSON DB
def export_data(self) -> dict:
# Конвертируем set в list для JSON-сериализации
return {"my_custom_set": list(self.non_db_data)}
def import_data(self, data: dict):
# Получаем данные и конвертируем обратно в set
self.non_db_data = set(data.get("my_custom_set", []))
```
--------------------------------
### CactusLib: Create Inline Markup
Source: https://cactus.den4iksop.org/dev/inline_keyboards
Assembles buttons into a complete inline keyboard markup. Can be configured as global, making the keyboard visible to all CactusLib users, or use a callback for post-sending actions. Dependencies: `CactusUtils.Inline.Markup`, `Callable`, `Optional` from `typing`.
```python
def __init__(self, is_global: bool = False, on_sent: Optional[Callable] = None, *args, **kwargs)
```
```python
# Создаем экземпляр разметки
markup = CactusUtils.Inline.Markup()
# Добавляем ряд с одной или несколькими кнопками
markup.add_row(button1, button2)
# Добавляем следующий ряд
markup.add_row(button3)
```
```python
# Создаем экземпляр разметки
markup = CactusUtils.Inline.Markup().add_row(button1, button2).add_row(button3)
```
--------------------------------
### Getting Sticker Set Info with get_sticker_set_by_short_name
Source: https://cactus.den4iksop.org/dev/advanced/rpc_calls
Obtain information about a sticker set using its short name. The `get_sticker_set_by_short_name` method requires the short name (e.g., 'CactusPlugins') and returns details about the sticker set. Error handling for cases where the sticker pack is not found is included.
```python
try:
result = self.utils.Telegram.get_sticker_set_by_short_name("CactusPlugins")
sticker_set = result.response.set
self.utils.show_info(f"Найден стикерпак: {sticker_set.title}")
except self.utils.Telegram.TLRPCException as e:
self.error(f"Стикерпак не найден: {e.error.text}")
```
--------------------------------
### CactusLib: Create Callback Data
Source: https://cactus.den4iksop.org/dev/inline_keyboards
Constructs data for a button's callback, specifying the target plugin and method to be invoked upon interaction. Allows passing additional keyword arguments. Dependencies: `CactusUtils.Inline.CallbackData`.
```python
CactusUtils.Inline.CallbackData(
plugin_id: str,
method: str,
# ... другие
**kwargs
)
```
```python
# Создаем кнопку с колбэком
button = CactusUtils.Inline.Button(
text="Нажми меня",
callback_data=CactusUtils.Inline.CallbackData(
plugin_id=self.id,
method="on_button_click",
arg1="value1",
arg2="value2",
# ...
)
)
```
--------------------------------
### Retrieving User Photos with get_user_photos
Source: https://cactus.den4iksop.org/dev/advanced/rpc_calls
Fetch a user's profile photos using the `get_user_photos` method. This method takes a `user_id` and an optional `limit` parameter to control the number of photos returned. The example shows how to count the retrieved photos and handle potential `TLRPCException` errors.
```python
try:
result = self.utils.Telegram.get_user_photos(user_id, limit=3)
photo_count = len(result.response.photos)
self.utils.show_info(f"Найдено {photo_count} фото.")
except self.utils.Telegram.TLRPCException as e:
self.error(f"Не удалось получить фото: {e.error.text}")
```
--------------------------------
### Generate and Use Uri with CactusUtils
Source: https://cactus.den4iksop.org/dev/advanced/utils
Demonstrates how to create and represent URI strings using the CactusUtils.Uri class. This includes creating instances directly or using the class method `create` and accessing the string representation of the URI.
```Python
from urllib.parse import unquote_plus
class MockPlugin:
def __init__(self, _id):
self.id = _id
def func(self):
# Создать Uri с использованием метода класса
uri_instance = CactusUtils.Uri.create(self, "open_settings", theme="dark", version="1.0")
print(f"Сгенерированный URI: {uri_instance}")
# Создать экземпляр Uri вручную
another_uri = CactusUtils.Uri(
plugin_id=self.id,
command="open_profile",
kwargs={"user_id": "12345", "tab": "posts"}
)
print(f"Другая строка URI: {another_uri.string()}")
```
--------------------------------
### Импорт CactusLib в Python
Source: https://cactus.den4iksop.org/dev/getting_started
Импортирует необходимые компоненты из библиотеки CactusLib. Включает обработку исключений на случай, если библиотека не установлена, прерывая загрузку плагина.
```python
try:
# Главный класс-обертка и декораторы
from cactuslib import CactusUtils, command, uri, message_uri
except (ImportError, ModuleNotFoundError):
# Если CactusLib не найден, лучше прервать загрузку плагина.
raise Exception("Необходим CactusLib. Пожалуйста, установите его.")
```
--------------------------------
### Runtime Execution
Source: https://cactus.den4iksop.org/dev/advanced/utils
Executes shell commands using Android's Runtime.getRuntime().exec().
```APIDOC
## `CactusUtils.runtime_exec(cmd: List[str], return_list_lines: bool = False, raise_errors: bool = True) -> Union[List[str], str]`
Executes a command using `Runtime.getRuntime().exec()` (equivalent to shell commands in Android/Java).
* **`cmd`**(List[str]): A list of strings representing the command and its arguments.
* **`return_list_lines`**(bool, optional): If `True`, returns the output as a list of strings. Otherwise, returns a single string with lines joined by newlines. Defaults to `False`.
* **`raise_errors`**(bool, optional): If `True`, runtime exceptions will be re-raised. Defaults to `True`.
#### Example Usage:
```python
# Get basic system info (example for Android environment)
# result_list = CactusUtils.runtime_exec(["getprop", "ro.build.version.release"], return_list_lines=True)
# print(f"Android version: {result_list[0]}")
# result_string = CactusUtils.runtime_exec(["ls", "-la", "/data/data"], return_list_lines=False)
# print(f"Partial listing of /data/data:\n{result_string[:200]}...")
```
```
--------------------------------
### FileSystem.write_file(file_path, content, mode: str = "wb")
Source: https://cactus.den4iksop.org/dev/advanced/utils
Writes content to a specified file. Supports writing both binary and string data.
```APIDOC
## FileSystem.write_file(file_path, content, mode: str = "wb")
### Description
Writes the provided `content` to the file specified by `file_path`. The `mode` parameter determines how the file is written to.
### Method
N/A (This appears to be a static method call or a function)
### Endpoint
N/A
### Parameters
#### Path Parameters
- **`file_path`** (str) - Required - The path to the file.
- **`content`** (bytes or str) - Required - The content to write to the file.
#### Query Parameters
- **`mode`** (str) - Optional - The file opening mode. Defaults to `"wb"` (write binary).
### Request Example
```python
output_file = CactusUtils.FileSystem.basedir("output.txt").getAbsolutePath()
CactusUtils.FileSystem.write_file(output_file, "This is some text.", mode="w")
print(f"Content written to: {output_file}")
binary_data = b"\x01\x02\x03\x04"
binary_file = CactusUtils.FileSystem.cachedir("binary_data.bin").getAbsolutePath()
CactusUtils.FileSystem.write_file(binary_file, binary_data)
print(f"Binary data written to: {binary_file}")
```
### Response
#### Success Response (200)
- **`status`** (str) - Indicates the success of the operation, e.g., "File written successfully."
#### Response Example
```json
{
"status": "File written successfully."
}
```
```
--------------------------------
### Manage File System Directories with CactusUtils.FileSystem.basedir
Source: https://cactus.den4iksop.org/dev/advanced/utils
The FileSystem.basedir() method returns the application's base directory and can create subdirectories if path components are provided. It ensures the existence of the specified directory structure within the app's data directory.
```python
# Get the base directory
base_dir = CactusUtils.FileSystem.basedir()
print(f"Base directory: {base_dir.getAbsolutePath()}")
# Get and create a subdirectory
my_data_dir = CactusUtils.FileSystem.basedir("my_app_data", "configs")
print(f"My data directory: {my_data_dir.getAbsolutePath()}")
# This will create 'my_app_data' and 'configs' if they don't exist.
```
--------------------------------
### CactusLib: Create Inline Button
Source: https://cactus.den4iksop.org/dev/inline_keyboards
Creates a single inline button for Telegram. Supports text, URLs, callback data, inline queries, and copy-to-clipboard functionality. Text can include custom emojis and icons. Dependencies: `Optional` from `typing`.
```python
CactusUtils.Inline.Button(
text: str,
# Один из следующих аргументов обязателен:
url: Optional[str] = None,
callback_data: Optional[str] = None,
query: Optional[str] = None,
copy: Optional[str] = None,
# ... другие
)
```
--------------------------------
### Create MessageUri with CactusUtils
Source: https://cactus.den4iksop.org/dev/advanced/utils
Illustrates the creation of MessageUri instances, a subclass of Uri specifically for message-related URIs. It shows how to use the `create` method to generate message URIs with associated chat and text parameters.
```Python
# Создать MessageUri
message_uri = CactusUtils.MessageUri.create(self, "send_message", chat_id=98765, text="Привет мир!")
print(f"Сгенерированный URI сообщения: {message_uri}")
```
--------------------------------
### FileSystem.cachedir(*path: str)
Source: https://cactus.den4iksop.org/dev/advanced/utils
Returns the application's external cache directory. It can create subdirectories within the cache directory.
```APIDOC
## FileSystem.cachedir(*path: str)
### Description
Returns the application's external cache directory. It can create subdirectories within the cache directory.
### Method
N/A (This appears to be a static method call or a function)
### Endpoint
N/A
### Parameters
#### Path Parameters
- **`*path`** (str) - Optional - Optional path components to append to the cache directory.
### Request Example
```python
# Get the cache directory
cache_dir = CactusUtils.FileSystem.cachedir()
print(f"Cache directory: {cache_dir.getAbsolutePath()}")
# Get and create a temporary cache subdirectory
temp_cache_dir = CactusUtils.FileSystem.cachedir("temp_images")
print(f"Temporary image directory: {temp_cache_dir.getAbsolutePath()}")
```
### Response
#### Success Response (200)
- **`cache_dir`** (Directory Object) - An object representing the cache directory or subdirectory.
#### Response Example
```json
{
"getAbsolutePath": "/path/to/app/cache/or/temp_images"
}
```
```
--------------------------------
### Создание базового класса плагина Python
Source: https://cactus.den4iksop.org/dev/getting_started
Определяет основной класс плагина, который должен наследоваться от `CactusUtils.Plugin`. Этот класс предоставляет доступ ко всем утилитам CactusLib и служит основой для функциональности плагина.
```python
__name__ = "Мой Первый Плагин"
__description__ = "Плагин, который приветствует мир."
__id__ = "my_first_plugin"
__version__ = "1.0"
__author__ = "@MyUsername"
# ... импорты ...
class MyFirstPlugin(CactusUtils.Plugin):
# Здесь будет логика вашего плагина
pass
```
--------------------------------
### FileSystem.write_temp_file(filename: str, content, mode="wb", delete_after: int = 0)
Source: https://cactus.den4iksop.org/dev/advanced/utils
Writes content to a file in the temporary directory. Optionally deletes the file after a specified delay.
```APIDOC
## FileSystem.write_temp_file(filename: str, content, mode="wb", delete_after: int = 0)
### Description
Writes the provided `content` to a file in the temporary directory. The file can be optionally deleted after a specified delay.
### Method
N/A (This appears to be a static method call or a function)
### Endpoint
N/A
### Parameters
#### Path Parameters
- **`filename`** (str) - Required - The name of the file in the temporary directory.
- **`content`** - Required - The content to write to the file.
#### Query Parameters
- **`mode`** (str) - Optional - The file opening mode. Defaults to `"wb"`.
- **`delete_after`** (int) - Optional - The number of seconds after which the file will be deleted. If 0, the file is not automatically deleted. Defaults to 0.
### Request Example
```python
temp_report_name = "report.csv"
temp_report_content = "Name,Age\nIvan,30\nMaria,25"
path_to_report = CactusUtils.FileSystem.write_temp_file(temp_report_name, temp_report_content, mode="w")
print(f"Report written to temporary file: {path_to_report}")
# Example for writing a temporary image that will be deleted after 10 seconds
# CactusUtils.FileSystem.write_temp_file("image.jpg", b"dummy_image_data", delete_after=10)
```
### Response
#### Success Response (200)
- **`path`** (str) - The full path to the created temporary file.
#### Response Example
```json
{
"path": "/path/to/app/cache/cactuslib_temp_files/report.csv"
}
```
```
--------------------------------
### FileSystem.tempdir()
Source: https://cactus.den4iksop.org/dev/advanced/utils
Returns a special temporary directory within the cache directory (`cactuslib_temp_files`). This directory is created if it does not exist.
```APIDOC
## FileSystem.tempdir()
### Description
Returns a special temporary directory within the cache directory (`cactuslib_temp_files`). This directory is created if it does not exist.
### Method
N/A (This appears to be a static method call or a function)
### Endpoint
N/A
### Parameters
None
### Request Example
```python
temp_dir = CactusUtils.FileSystem.tempdir()
print(f"CactusLib temporary directory: {temp_dir.getAbsolutePath()}")
```
### Response
#### Success Response (200)
- **`temp_dir`** (Directory Object) - An object representing the temporary directory.
#### Response Example
```json
{
"getAbsolutePath": "/path/to/app/cache/cactuslib_temp_files"
}
```
```
--------------------------------
### Implement a command dependent on plugin settings in Python
Source: https://cactus.den4iksop.org/dev/commands
This Python snippet illustrates how to create a command that is conditionally enabled based on a plugin setting. The `create_settings` method defines a `Switch` setting named 'extra_feature_enabled'. The `@command` decorator uses the `enabled` argument to link the `extra_cmd` to this setting, ensuring it only functions when the feature is enabled by the user.
```python
class MyPlugin(CactusUtils.Plugin):
def create_settings(self):
# В настройках плагина
return [Switch(key="extra_feature_enabled", text="Включить фичу X", default=False)]
@command(doc="Команда для фичи X", enabled="extra_feature_enabled")
def extra_cmd(self, cmd: CactusUtils.Command):
cmd.answer("Фича X работает!")
return HookResult(strategy=HookStrategy.CANCEL)
```
--------------------------------
### CactusLib: Registering Commands with @command Decorator
Source: https://cactus.den4iksop.org/dev/commands
The @command decorator is used to register commands that users can invoke. It allows specifying the command name, aliases, a description key for help menus, and conditional enabling based on plugin settings.
```python
@command(
command: Optional[str] = None,
aliases: Optional[List[str]] = None,
doc: Optional[str] = None,
enabled: Optional[Union[str, bool]] = None
)
```
--------------------------------
### Compress and Encode Data (Python)
Source: https://cactus.den4iksop.org/dev/advanced/utils
Compresses data using zlib and then encodes it using base64. Accepts either bytes or string input. The compression level can be adjusted.
```python
original_text = "Это пример текста, который будет сжат и закодирован."
encoded_text = CactusUtils.compress_and_encode(original_text)
print(f"Исходная длина: {len(original_text)}")
print(f"Сжатая и закодированная длина: {len(encoded_text)}")
print(f"Закодированные данные: {encoded_text[:50]}...")
```
--------------------------------
### Создание и обработка глобальных URI в Python
Source: https://cactus.den4iksop.org/dev/uri_handlers
Этот пример демонстрирует, как создать глобальный URI с помощью декоратора `@uri` и как получить аргументы из этого URI в функции-обработчике. Также показано, как сгенерировать ссылку с помощью `self.utils.Uri.create()`.
```python
class MyPlugin(CactusUtils.Plugin):
@uri("notify")
def _on_notify_uri(self, text: str, user: str = "Anonymous"):
# Показываем системное уведомление (bulletin)
self.utils.show_info(f"Уведомление от {user}: {text}")
@command(doc="Генерирует ссылку для уведомления")
def make_link(self, cmd: CactusUtils.Command):
# Создаем URI с помощью утилиты
link = self.utils.Uri.create(self, "notify", text="Hello from URI!", user="Admin")
# link будет "tg://cactus/my_plugin_id/notify?text=Hello+from+URI%21&user=Admin"
self.answer(cmd.params, f"Нажмите на эту ссылку: {link}")
```
--------------------------------
### CactusLib: Accessing Command Information within a Handler
Source: https://cactus.den4iksop.org/dev/commands
The `CactusUtils.Command` object is passed to command handler functions, providing access to the invoked command name, arguments, raw input, original message text, and message parameters. It also offers utility methods for answering messages and converting message text to HTML or Markdown.
```python
cmd.command: str # The command or alias used.
cmd.args: List[str] # Parsed arguments after the command.
cmd.raw_args: str # The raw string of arguments.
cmd.text: str # The full original message text.
cmd.params: Any # Object with original message parameters (e.g., peer, replyToMsg).
cmd.answer(text: str, **kwargs) # Helper to send a reply message.
cmd.html() -> str # Returns message text with HTML formatting.
cmd.markdown() -> str # Returns message text with Markdown formatting.
```
--------------------------------
### Executing Shell Commands with CactusUtils.runtime_exec
Source: https://cactus.den4iksop.org/dev/advanced/utils
The runtime_exec function executes shell commands using Java's Runtime.getRuntime().exec(). It can return output as a list of lines or a single string and allows control over error raising. This is useful for interacting with the underlying Android/Java environment.
```python
# Получить основную системную информацию (пример для среды Android)
# result_list = CactusUtils.runtime_exec(["getprop", "ro.build.version.release"], return_list_lines=True)
# print(f"Версия Android: {result_list[0]}")
# result_string = CactusUtils.runtime_exec(["ls", "-la", "/data/data"], return_list_lines=False)
# print(f"Частичный листинг /data/data:\n{result_string[:200]}...")
```
--------------------------------
### FileSystem.get_file_content(file_path, mode: str = "rb")
Source: https://cactus.den4iksop.org/dev/advanced/utils
Reads the content of a file. Supports binary or text modes.
```APIDOC
## FileSystem.get_file_content(file_path, mode: str = "rb")
### Description
Reads the content of a file specified by `file_path`. The `mode` parameter determines how the file is read.
### Method
N/A (This appears to be a static method call or a function)
### Endpoint
N/A
### Parameters
#### Path Parameters
- **`file_path`** (str) - Required - The path to the file.
#### Query Parameters
- **`mode`** (str) - Optional - The file opening mode. Defaults to `"rb"` (read binary).
### Request Example
```python
# Assuming 'my_file.txt' exists in the basedir
file_path = CactusUtils.FileSystem.basedir("my_file.txt").getAbsolutePath()
# First, write some content to the file for demonstration
CactusUtils.FileSystem.write_file(file_path, "Hello, world!", mode="w")
content_bytes = CactusUtils.FileSystem.get_file_content(file_path)
print(f"Content (bytes): {content_bytes}")
content_str = CactusUtils.FileSystem.get_file_content(file_path, mode="r")
print(f"Content (string): {content_str}")
```
### Response
#### Success Response (200)
- **`content`** (bytes or str) - The content of the file, either as bytes or a string, depending on the `mode`.
#### Response Example
```json
{
"content": "Hello, world!"
}
```
```
--------------------------------
### Decode and Decompress Data (Python)
Source: https://cactus.den4iksop.org/dev/advanced/utils
Decodes data from base64 encoding and then decompresses it using zlib. Expects data that has been previously compressed and encoded by `compress_and_encode`. Returns bytes.
```python
original_text = "Еще один фрагмент текста для демонстрации декодирования и декомпрессии."
encoded_text = CactusUtils.compress_and_encode(original_text)
decoded_bytes = CactusUtils.decode_and_decompress(encoded_text)
decoded_text = decoded_bytes.decode('utf-8')
print(f"Декодированный и декомпрессированный текст: {decoded_text}")
```