### Bot Initialization Setup Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/project-overview.md Example of using the `@cli.on_init` decorator to perform setup tasks when the bot starts. This snippet shows how to iterate through all account IDs and set a configuration value, such as the display name. ```python @cli.on_init def setup(bot, args): for accid in bot.rpc.get_all_account_ids(): bot.rpc.set_config(accid, "displayname", "MyBot") ``` -------------------------------- ### Example Usage for Multiple Accounts Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/usage-patterns.md Command-line examples for initializing, listing, and serving bots with multiple accounts. ```bash # Setup multiple accounts ./multibot init account1@example.com password1 ./multibot init account2@example.com password2 # List accounts ./multibot list # Output: # #1 - account1@example.com # #2 - account2@example.com # Serve all accounts ./multibot serve # Or serve specific account ./multibot serve --account 1 ``` -------------------------------- ### Start BotCli Application Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli.md This is the main entry point for the bot CLI. It parses command-line arguments and initiates the bot's operation. Ensure this is called at the end of your bot's setup. ```python if __name__ == "__main__": cli = BotCli("mybot") @cli.on(events.NewMessage) def handle_msg(bot, accid, event): pass cli.start() ``` -------------------------------- ### BotCli.start() Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/REFERENCE.md Starts the CLI, processes command-line arguments, and executes the appropriate logic. ```APIDOC ## BotCli.start() ### Description Starts the CLI, processes command-line arguments, and executes the appropriate logic. ### Method N/A (Instance Method) ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from deltabot_cli import BotCli cli = BotCli("MyBot") # cli.start() # This would typically be called at the end of a script ``` ### Response #### Success Response (200) None #### Response Example N/A ``` -------------------------------- ### start Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli.md Starts the bot CLI, processes command-line arguments, and executes the specified subcommand. This method serves as the primary entry point for the CLI application. ```APIDOC ## Method: `start` ### Description Start the bot CLI, parse command-line arguments, and run the specified subcommand. This is the main entry point and should be called at the end of bot setup. ### Signature ```python def start(self) -> None ``` ### Returns - **None** ### Throws - **SystemExit** - When the CLI exits (normal execution or error) ### Example ```python if __name__ == "__main__": cli = BotCli("mybot") @cli.on(events.NewMessage) def handle_msg(bot, accid, event): pass cli.start() ``` ``` -------------------------------- ### Install deltabot-cli Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/README.md Use pip to install the deltabot-cli package. ```sh pip install deltabot-cli ``` -------------------------------- ### Start Event Loop Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli-internal-methods.md Entry point for the event loop in `_serve_cmd`. It can listen to a specific account or all accounts. ```python bot.run_forever(accounts[0] if args.account else 0) ``` -------------------------------- ### BotCli.on_start() Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/REFERENCE.md Registers a hook that runs once when the CLI starts processing arguments. ```APIDOC ## BotCli.on_start() ### Description Registers a hook that runs once when the CLI starts processing arguments. ### Method N/A (Instance Method) ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from deltabot_cli import BotCli cli = BotCli("MyBot") @cli.on_start() def start_bot(args): print("Bot starting...") ``` ### Response #### Success Response (200) Returns the registered CliEventHook function. #### Response Example N/A ``` -------------------------------- ### Example CmdCallback Usage Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/types.md Registering a subcommand to send a message, defining its arguments and callback function. ```python from deltabot_cli import BotCli from argparse import Namespace from deltachat2 import Bot, MsgData cli = BotCli("mybot") def send_message(cli_instance: BotCli, bot: Bot, args: Namespace) -> None: """Send a message to a specific chat""" accid = bot.rpc.get_all_account_ids()[0] bot.rpc.send_msg(accid, args.chat_id, MsgData(text=args.text)) send_parser = cli.add_subcommand(send_message) send_parser.add_argument("chat_id", type=int) send_parser.add_argument("text") ``` -------------------------------- ### Application Entry Point Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/project-overview.md Typical application structure for initializing and starting a deltabot CLI application. Register handlers before calling start(). ```python if __name__ == "__main__": cli = BotCli("app_name") # ... register handlers ... cli.start() # Main entry point ``` -------------------------------- ### Example Namespace Usage Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/types.md Demonstrates creating and populating an argparse Namespace object with common bot arguments. ```python from argparse import Namespace args = Namespace() args.account = 1 args.config_dir = "/home/user/.config/mybot" args.logging = "debug" ``` -------------------------------- ### Example Usage for One-Shot Message Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/usage-patterns.md Command-line examples for sending text messages or messages with attachments using the one-shot pattern. ```bash ./sendbot send "Hello admin" ./sendbot send "Here's a file" /path/to/file.txt ``` -------------------------------- ### Error Handling Example Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/REFERENCE.md Example demonstrating how to handle `JsonRpcError` exceptions that can be raised by RPC operations. ```APIDOC ## Error Handling ### Exception: JsonRpcError From deltachat2 library. Raised by all RPC operations. ```python from deltachat2 import JsonRpcError try: bot.rpc.send_msg(accid, chatid, MsgData(text="Hello")) except JsonRpcError as e: bot.logger.error(f"RPC error: {e}") ``` ``` -------------------------------- ### Example CLI Usage with Default Options Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/configuration.md Demonstrates how to use the default CLI options like --config-dir, --account, and --logging for different bot commands. ```bash ./mybot init -c /home/user/.mybot user@example.com password ./mybot serve --account 1 ./mybot config -l debug ``` -------------------------------- ### Minimal Echo Bot Example Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/index.md A basic Python script demonstrating how to create an echo bot using deltabot-cli. It initializes the bot, registers a handler for new messages, and sends back the received message text. Ensure you have deltachat2 installed. ```python from deltabot_cli import BotCli from deltachat2 import events, MsgData cli = BotCli("echobot") @cli.on(events.NewMessage) def echo(bot, accid, event): msg = event.msg bot.rpc.send_msg(accid, msg.chat_id, MsgData(text=msg.text)) if __name__ == "__main__": cli.start() ``` -------------------------------- ### Install deltabot-cli Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/index.md Install the deltabot-cli library using pip. This command is used to set up the necessary packages for building Delta Chat bot command-line interfaces. ```bash pip install deltabot-cli ``` -------------------------------- ### Running the Bot CLI Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/REFERENCE.md Call the `start()` method on the BotCli instance to run the bot application and begin processing commands and events. ```python cli.start() ``` -------------------------------- ### Setup IOTransport and Rpc Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli-internal-methods.md Initializes IOTransport and Rpc. Stderr is suppressed when not in DEBUG mode. ```python kwargs = {"stderr": subprocess.DEVNULL} if log_level > logging.DEBUG else {} with IOTransport(accounts_dir=accounts_dir, **kwargs) as trans: rpc = Rpc(trans) self._bot = Bot(rpc, self._hooks, logger) ``` -------------------------------- ### Filter NewMessage Events by Command Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/types.md Example of using EventFilter to trigger a handler only when a message starts with the /help command. ```python from deltachat2 import events @cli.on(events.NewMessage(command="/help")) def handle_help(bot, accid, event): """Only triggered when message starts with /help""" pass ``` -------------------------------- ### Example CliEventHook Usage Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/types.md Registering an initialization hook to set a bot's display name for all accounts. ```python from deltabot_cli import BotCli from argparse import Namespace from deltachat2 import Bot cli = BotCli("mybot") @cli.on_init def initialize(bot: Bot, args: Namespace) -> None: bot.logger.info("Initializing bot") for accid in bot.rpc.get_all_account_ids(): bot.rpc.set_config(accid, "displayname", "MyBot") ``` -------------------------------- ### Registering a start event hook Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli.md Register a function to be called when the bot is about to start serving requests. This is useful for initializing background tasks or resources before the bot becomes active. ```APIDOC ## Method: `on_start` ### Description Register a function to be called when the bot is about to start serving requests (after initialization, before event loop begins). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **func** (CliEventHook) - Required - A callable with signature `(bot: Bot, args: Namespace) -> None` ### Returns `CliEventHook` — The function itself (for decorator use) ### Throws None ### Example: ```python @cli.on_start def start_background_tasks(bot, args): bot.logger.info("Starting background tasks...") # Connect to databases, start worker threads, etc. ``` ``` -------------------------------- ### Bot with Initialization Hooks Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/usage-patterns.md A bot that demonstrates setup procedures during initialization. It configures accounts, sets display names and statuses, and retrieves admin chats. The `on_start` hook is used to signal readiness. ```python from deltachat2 import events from deltabot_cli import BotCli cli = BotCli("mybot") @cli.on_init def setup_bot(bot, args): bot.logger.info("Setting up bot...") for accid in bot.rpc.get_all_account_ids(): # Configure the account bot.rpc.set_config(accid, "displayname", "MyBot") bot.rpc.set_config(accid, "selfstatus", "I'm a helpful bot") # Create/get admin chat admin_chat = cli.get_admin_chat(bot.rpc, accid) bot.logger.info(f"Admin chat: {admin_chat}") @cli.on_start def on_start(bot, args): bot.logger.info("Bot is now ready to receive messages") # Start background tasks, connect to databases, etc. @cli.on(events.NewMessage) def handle_message(bot, accid, event): bot.logger.info(f"Got message: {event.msg.text}") if __name__ == "__main__": cli.start() ``` -------------------------------- ### Running the deltabot-cli Application Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/index.md Commands to initialize a bot account and start the bot's event loop. The 'init' command sets up a new user account, while 'serve' runs the bot to process events. ```bash python echobot.py init user@example.com password ``` ```bash python echobot.py serve ``` -------------------------------- ### Deltabot-CLI Module Structure Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/project-overview.md Shows the directory and file structure of the deltabot-cli Python package and its examples. ```text deltabot_cli/ ├── __init__.py → Exports BotCli ├── cli.py → Main BotCli class and default subcommands └── _utils.py → ConfigProgressBar, parse_docstring examples/ ├── echobot.py → Minimal echo bot example ├── echobot_advanced.py → Advanced echo bot with hooks and filtering └── send_and_exit.py → One-shot message sender example ``` -------------------------------- ### Start Bot Message Processing Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/subcommands.md This command starts the bot's main event loop to process incoming messages and events. It can operate on a specific account ID and allows setting the logging level. The bot logs a connection QR code and calls on_start hooks. ```bash ./mybot serve ``` ```bash ./mybot serve --account 1 ``` ```bash ./mybot serve -l debug ``` -------------------------------- ### Register Bot Start Event Hook Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli.md Register a function to be called after bot initialization but before the event loop starts. Useful for setting up background tasks. ```python cli.on_start def start_background_tasks(bot, args): bot.logger.info("Starting background tasks...") # Connect to databases, start worker threads, etc. ``` -------------------------------- ### on_init Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli.md Registers a function to be called before the bot starts serving requests. This is useful for initializing state, loading configuration, or setting up databases. ```APIDOC ## Method: `on_init` ### Description Register a function to be called before the bot starts serving requests. Useful for initializing state, loading configuration, or setting up databases. ### Method Signature ```python def on_init(self, func: CliEventHook) -> CliEventHook ``` ### Parameters #### Path Parameters - **func** (CliEventHook) - Yes - A callable with signature `(bot: Bot, args: Namespace) -> None` ### Returns `CliEventHook` — The function itself (for decorator use) ### Throws None ### Example ```python @cli.on_init def initialize_bot(bot, args): bot.logger.info("Initializing bot...") for accid in bot.rpc.get_all_account_ids(): if not bot.rpc.get_config(accid, "displayname"): bot.rpc.set_config(accid, "displayname", "MyBot") ``` ``` -------------------------------- ### Initialize and Run a Bot Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/index.md Initialize the BotCli with a name and log level, set up event handlers, and start the bot. This is the main entry point for a Deltabot CLI application. ```python from deltabot_cli import BotCli from deltachat2 import events cli = BotCli("mybot", log_level="info") @cli.on_init def setup(bot, args): # Configure accounts pass @cli.on(events.NewMessage) def handle(bot, accid, event): # Process messages pass if __name__ == "__main__": cli.start() ``` -------------------------------- ### Command-Based Bot Example Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/usage-patterns.md A bot that responds to specific commands like /help, /ping, and /status. It also includes a default handler for non-command messages. ```python from deltachat2 import MsgData, events from deltabot_cli import BotCli cli = BotCli("commandbot") @cli.on(events.NewMessage(command="/help")) def help_command(bot, accid, event): msg = event.msg help_text = """Available commands: /help - Show this help message /ping - Respond with pong /status - Show bot status""" bot.rpc.send_msg(accid, msg.chat_id, MsgData(text=help_text)) @cli.on(events.NewMessage(command="/ping")) def ping_command(bot, accid, event): msg = event.msg bot.rpc.send_msg(accid, msg.chat_id, MsgData(text="Pong!")) @cli.on(events.NewMessage(command="/status")) def status_command(bot, accid, event): msg = event.msg status = "Bot is running normally" bot.rpc.send_msg(accid, msg.chat_id, MsgData(text=status)) @cli.on(events.NewMessage(is_info=False)) def default_handler(bot, accid, event): # Ignore messages that aren't commands if bot.has_command(event.command): return msg = event.msg bot.logger.info(f"Regular message: {msg.text}") if __name__ == "__main__": cli.start() ``` ```bash ./commandbot serve # User sends: /help → Bot responds with help # User sends: /ping → Bot responds with: Pong! ``` -------------------------------- ### Complete Deltabot CLI Usage Pattern Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/REFERENCE.md A comprehensive example demonstrating the typical structure of a Deltabot CLI application. It includes initialization, startup hooks, event handling for new messages, cleanup actions, and custom subcommand definition. ```python from deltabot_cli import BotCli from deltachat2 import events, MsgData # Create bot cli = BotCli("mybot", log_level="info") # Initialization hook @cli.on_init def setup(bot, args): for accid in bot.rpc.get_all_account_ids(): bot.rpc.set_config(accid, "displayname", "MyBot") # Startup hook @cli.on_start def ready(bot, args): bot.logger.info("Ready to receive messages") # Event handler @cli.on(events.NewMessage) def handle_message(bot, accid, event): msg = event.msg bot.logger.info(f"Got: {msg.text}") bot.rpc.send_msg(accid, msg.chat_id, MsgData(text="Reply")) # Cleanup handler @cli.after(events.NewMessage) def cleanup(bot, accid, event): bot.rpc.delete_messages(accid, [event.msg.id]) # Custom subcommand def custom(cli_inst, bot, args): """Do something""" bot.logger.info("Custom command") if __name__ == "__main__": cli.add_subcommand(custom) cli.start() ``` -------------------------------- ### Configuration RPC Methods Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/REFERENCE.md Methods for getting and setting configuration values for a specific Delta Chat account. ```APIDOC ## Configuration ### get_config Retrieves a configuration value for a given account and key. - **Parameters**: - **accid** (`int`) - Required - The ID of the account. - **key** (`str`) - Required - The configuration key. - **Returns**: `str | None` - The configuration value, or None if not found. ### set_config Sets a configuration value for a given account and key. - **Parameters**: - **accid** (`int`) - Required - The ID of the account. - **key** (`str`) - Required - The configuration key. - **value** (`str`) - Required - The configuration value to set. ``` -------------------------------- ### Get Accounts Directory Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli-internal-methods.md Resolves the accounts directory path. The directory is created if it does not already exist. ```python accounts_dir = self.get_accounts_dir(args) # Returns: /accounts ``` -------------------------------- ### Add Custom Subcommands to CLI Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/usage-patterns.md Extend the BotCli with custom subcommands to perform specific actions. This example shows how to add 'notify' and 'accounts' subcommands. ```python from deltachat2 import MsgData from deltabot_cli import BotCli from argparse import Namespace cli = BotCli("botwithtasks") def send_notification(cli_inst, bot, args): """Send a notification to the admin chat""" accid = bot.rpc.get_all_account_ids()[0] admin_chat = cli_inst.get_admin_chat(bot.rpc, accid) text = f"Notification: {args.message}" if args.emoji: text = f"{args.emoji} {text}" bot.rpc.send_msg(accid, admin_chat, MsgData(text=text)) bot.logger.info("Notification sent") def list_accounts(cli_inst, bot, args): """List all accounts in a formatted way""" accounts = bot.rpc.get_all_account_ids() print(f"Total accounts: {len(accounts)}") for accid in accounts: transports = bot.rpc.list_transports(accid) for t in transports: print(f" Account {accid}: {t['addr']}") if __name__ == "__main__": # Add custom subcommands notify_cmd = cli.add_subcommand(send_notification, name="notify") notify_cmd.add_argument("message", help="Message to send") notify_cmd.add_argument("--emoji", help="Emoji prefix") cli.add_subcommand(list_accounts, name="accounts") cli.start() ``` -------------------------------- ### Admin-Only Commands Example Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/usage-patterns.md This bot restricts certain commands, like /announce, to administrators only. It checks user permissions before executing the command logic. ```python from deltachat2 import MsgData, events from deltabot_cli import BotCli cli = BotCli("adminbot") @cli.on(events.NewMessage(command="/announce")) def announce_command(bot, accid, event): msg = event.msg # Check if user is admin if not cli.is_admin(bot.rpc, accid, msg.from_id): bot.rpc.send_msg( accid, msg.chat_id, MsgData(text="You don't have permission to use this command") ) return # Only admins can reach here bot.logger.info(f"Admin announcement from {msg.from_id}: {msg.text}") # Broadcast to all chats, save to database, etc. if __name__ == "__main__": cli.start() ``` -------------------------------- ### Get Configuration Value Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/rpc-methods.md Retrieves a specific configuration value for an account. Use when you need to read a setting like the display name. ```python name = bot.rpc.get_config(accid, "displayname") if name: bot.logger.info(f"Bot name: {name}") ``` -------------------------------- ### Get Specific Bot Configuration Value Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/subcommands.md Retrieve the current value of a specific configuration key for all accounts. Provide the configuration key as an argument. ```bash ./mybot config displayname ``` -------------------------------- ### Create an Echo Bot with deltabot-cli Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/README.md Example of an echo bot using deltabot-cli. It logs all raw events and echoes back new messages. Ensure necessary imports are present. ```python from deltachat2 import MsgData, events from deltabot_cli import BotCli cli = BotCli("echobot") @cli.on(events.RawEvent) def log_event(bot, accid, event): bot.logger.info(event) @cli.on(events.NewMessage) def echo(bot, accid, event): msg = event.msg bot.rpc.send_msg(accid, msg.chat_id, MsgData(text=msg.text)) if __name__ == "__main__": cli.start() ``` -------------------------------- ### Basic Echo Bot Implementation Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/project-overview.md A minimal working echo bot that registers a single event handler for new messages and sends them back to the sender. This demonstrates the absolute minimum required to get a bot running. ```python from deltabot_cli import BotCli from deltachat2 import events, MsgData cli = BotCli("mybot") @cli.on(events.NewMessage) def echo(bot, accid, event): msg = event.msg bot.rpc.send_msg(accid, msg.chat_id, MsgData(text=msg.text)) if __name__ == "__main__": cli.start() ``` -------------------------------- ### Bot Logging Examples Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/index.md Use the bot logger to record debug, info, warning, error, and exception messages. Logging levels can be controlled via the constructor or CLI options. ```python bot.logger.debug("Debug message") bot.logger.info("Info message") bot.logger.warning("Warning message") bot.logger.error("Error message") bot.logger.exception(exception_obj) # Include traceback ``` -------------------------------- ### Initialize Bot Account Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/subcommands.md Use this command to set up a new bot account with email and password, or import from a QR code. It handles account creation, setting the 'bot' config, and displays progress. Configuration directory and logging level can be specified. ```bash ./mybot init user@example.com password ``` ```bash ./mybot init DCACCOUNT:nine.testrun.org ``` ```bash ./mybot init -c /custom/config/dir user@example.com password ``` ```bash ./mybot init --account 5 user@example.com password ``` -------------------------------- ### Initialize and Use ConfigProgressBar Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/ConfigProgressBar.md Demonstrates how to initialize the ConfigProgressBar, update its progress, and close it upon completion or error. ```python from deltabot_cli._utils import ConfigProgressBar pbar = ConfigProgressBar() pbar.set_progress(250) # Update to 25% complete pbar.set_progress(500) # Update to 50% complete pbar.close() # Finish the progress bar ``` -------------------------------- ### ConfigProgressBar.__init__ Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/ConfigProgressBar.md Initializes a new progress bar for account configuration. It sets up the progress tracking with a total of 1000 units. ```APIDOC ## Constructor: ConfigProgressBar.__init__ ### Description Initialize a new progress bar for account configuration. ### Returns None ### Properties: - `progress` (int) — Current progress value, ranges from 0 to total. Set to -1 on error. - `total` (int) — Total progress target, always 1000 - `tracker` — Internal rich progress tracker object ### Example: ```python from deltabot_cli._utils import ConfigProgressBar pbar = ConfigProgressBar() pbar.set_progress(250) # Update to 25% complete pbar.set_progress(500) # Update to 50% complete pbar.close() # Finish the progress bar ``` ``` -------------------------------- ### List All Bot Configurations Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/subcommands.md Use this command to display all available configuration keys and their current values for all accounts. No arguments are needed. ```bash ./mybot config ``` -------------------------------- ### BotCli.get_admin_chat() Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/REFERENCE.md Gets or creates the admin chat for a given account. ```APIDOC ## BotCli.get_admin_chat() ### Description Gets or creates the admin chat for a given account. ### Method N/A (Instance Method) ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from deltabot_cli import BotCli from deltabot_cli.rpc import Rpc cli = BotCli("MyBot") # Assume rpc and accid are initialized # admin_chat_id = cli.get_admin_chat(rpc, accid) ``` ### Response #### Success Response (200) Returns the admin chat ID as an integer. #### Response Example ``` 12345 ``` ``` -------------------------------- ### Initialize BotCli Instance Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli.md Create a new BotCli instance. You can specify the application name, logging level, and whether to add default subcommands. ```python from deltabot_cli import BotCli # Create a basic bot CLI cli = BotCli("mybot") # Create with custom log level cli = BotCli("mybot", log_level="debug") # Create without default subcommands cli = BotCli("mybot", add_defaults=False) ``` -------------------------------- ### Initialize Argument Parser Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli-internal-methods.md Sets up the ArgumentParser for the BotCli in its constructor. Subparsers are added for different commands. ```python self._parser = ArgumentParser(app_name) self._subparsers = self._parser.add_subparsers(title="subcommands") ``` -------------------------------- ### Usage of Custom Subcommands Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/usage-patterns.md Demonstrates how to invoke the custom subcommands added to the BotCli. ```bash ./botwithtasks notify "Server is online" --emoji "✅" ./botwithtasks accounts ./botwithtasks serve ``` -------------------------------- ### BotCli.on_init() Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/REFERENCE.md Registers a hook that runs once when the CLI is initialized. ```APIDOC ## BotCli.on_init() ### Description Registers a hook that runs once when the CLI is initialized. ### Method N/A (Instance Method) ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from deltabot_cli import BotCli cli = BotCli("MyBot") @cli.on_init() def initialize_bot(config): print("Bot initializing...") ``` ### Response #### Success Response (200) Returns the registered CliEventHook function. #### Response Example N/A ``` -------------------------------- ### BotCli Constructor Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli.md Initializes a new BotCli instance. You can specify the application name, logging level, and whether to add default subcommands. ```APIDOC ## BotCli.__init__ ### Description Initializes a new BotCli instance. You can specify the application name, logging level, and whether to add default subcommands. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **app_name** (str) - Required - Application name used in CLI help text and logging - **log_level** (str) - Optional - Default logging level; one of "debug", "info", "warning", "error". Defaults to "info". - **add_defaults** (bool) - Optional - If True, automatically adds default subcommands (init, serve, config, etc.) and generic options. Defaults to True. ### Returns None ### Example: ```python from deltabot_cli import BotCli # Create a basic bot CLI cli = BotCli("mybot") # Create with custom log level cli = BotCli("mybot", log_level="debug") # Create without default subcommands cli = BotCli("mybot", add_defaults=False) ``` ``` -------------------------------- ### Filter NewMessage Events by Info Status Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/types.md Example of using EventFilter to trigger a handler only for non-info messages. ```python from deltachat2 import events @cli.on(events.NewMessage(is_info=False)) def handle_user_message(bot, accid, event): """Only triggered for non-info messages""" pass ``` -------------------------------- ### BotCli Constructor Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/REFERENCE.md Initialize the BotCli class with an application name and optional logging level and default command settings. ```python def __init__( self, app_name: str, log_level: str = "info", add_defaults: bool = True ) -> None ``` -------------------------------- ### Filter for Admin Commands Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/event-handling.md Use this to process only messages that start with the '/admin' command. It checks if the sender is an administrator. ```python # Only admin commands @cli.on(events.NewMessage(command="/admin")) def admin_cmd(bot, accid, event): if cli.is_admin(bot.rpc, accid, event.msg.from_id): pass ``` -------------------------------- ### Creating a Bot Instance Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/REFERENCE.md Instantiate the BotCli class to create a new bot client. You can specify the application name, logging level, and whether to include default configurations. ```python cli = BotCli(app_name, log_level="info", add_defaults=True) ``` -------------------------------- ### BotCli _on_start Method Signature Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli-internal-methods.md This is the internal method signature for _on_start in BotCli. It is responsible for calling registered on_start hooks. ```python def _on_start(self, bot: Bot, args: Namespace) -> None ``` -------------------------------- ### Filter for File Attachments Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/event-handling.md This example processes messages that contain file attachments. It checks for the presence of a file in the message. ```python # File attachments @cli.on(events.NewMessage) def file_messages(bot, accid, event): if event.msg.file: pass ``` -------------------------------- ### Configuration Transfer RPC Methods Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/REFERENCE.md Methods for adding and updating transport configurations, often used for account setup. ```APIDOC ## Configuration Transfer ### add_transport_from_qr Adds a transport configuration from QR code data. - **Parameters**: - **accid** (`int`) - Required - The ID of the account. - **qr_data** (`str`) - Required - The QR code data string. ### add_or_update_transport Adds or updates a transport configuration using provided parameters. - **Parameters**: - **accid** (`int`) - Required - The ID of the account. - **params** (`dict`) - Required - A dictionary of transport parameters. ``` -------------------------------- ### Get All Account IDs Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/rpc-methods.md Retrieves a list of all configured account IDs. Useful for iterating through accounts to perform batch operations. ```python def get_all_account_ids() -> list[int]: pass ``` ```python @cli.on_init def setup_all_accounts(bot, args): for accid in bot.rpc.get_all_account_ids(): bot.logger.info(f"Setting up account {accid}") ``` -------------------------------- ### Minimal BotCli Initialization Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/configuration.md Initialize the BotCli with just the application name. This uses default settings for logging and command additions. ```python from deltabot_cli import BotCli # Minimal configuration cli = BotCli("mybot") ``` -------------------------------- ### Get Bot Accounts Directory Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli.md Retrieves the path to the directory where bot accounts are stored. The directory is created if it does not already exist. ```python def get_accounts_dir(self, args: Namespace) -> str: # ... implementation details ... pass # Example usage: accounts_dir = cli.get_accounts_dir(args) print(f"Accounts stored at: {accounts_dir}") ``` -------------------------------- ### Internal State Variable: _bot Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli-internal-methods.md The bot instance itself, created during the start() method. It is set after the IOTransport and Rpc are initialized and before any subcommand is executed. ```python self._bot: Bot ``` -------------------------------- ### Initialize Bot Before Serving Requests Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli.md The `on_init` decorator registers a function to execute before the bot begins handling requests. It's ideal for setting up initial bot state, loading configurations, or establishing database connections. ```python @cli.on_init def initialize_bot(bot, args): bot.logger.info("Initializing bot...") for accid in bot.rpc.get_all_account_ids(): if not bot.rpc.get_config(accid, "displayname"): bot.rpc.set_config(accid, "displayname", "MyBot") ``` -------------------------------- ### Get System Information Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/rpc-methods.md Retrieves system information, including the Delta Chat core version. Useful for diagnostics and compatibility checks. ```python def get_system_info() -> SystemInfo ``` ```python info = bot.rpc.get_system_info() bot.logger.info(f"Delta Chat core version: {info.deltachat_core_version}") ``` -------------------------------- ### Import BotCli Class Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/project-overview.md This snippet shows how to import the main BotCli class from the library. ```python from deltabot_cli import BotCli ``` -------------------------------- ### Print Bot Connection Link and QR Code Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/subcommands.md Prints the secure join QR code or link to connect to the bot for each configured account. This is useful for easily connecting new clients to your bot. ```bash ./mybot link ./mybot link --account 1 # Output: dcaccount:https://example.com/join/... ``` -------------------------------- ### Registering Pre-Event Handler with @cli.on() Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/event-handling.md Use the @cli.on() decorator to register a handler that executes before other handlers for the same event. This example logs new messages. ```python @cli.on(events.NewMessage) def handle_message(bot, accid, event): msg = event.msg bot.logger.info(f"Message: {msg.text}") ``` -------------------------------- ### Catch JsonRpcError Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli-internal-methods.md Example of catching and logging JsonRpcError, commonly raised by RPC operations. This is useful for handling configuration or invalid option errors. ```python except JsonRpcError as err: bot.logger.error(err) ``` -------------------------------- ### Internal State Variable: _start_hooks Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli-internal-methods.md A set containing startup hooks registered via the on_start() decorator. These hooks are executed when the bot begins serving, specifically in the _serve_cmd method. ```python self._start_hooks: set[CliEventHook] ``` -------------------------------- ### Import Internal Utilities Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/REFERENCE.md Import utility functions like ConfigProgressBar and parse_docstring from internal modules. ```python from deltabot_cli._utils import ConfigProgressBar, parse_docstring ``` -------------------------------- ### Get Chat Contacts Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/rpc-methods.md Fetch a list of contact IDs present in a chat using `get_chat_contacts`. This can be used to iterate through members and retrieve their details. ```python members = bot.rpc.get_chat_contacts(accid, chatid) for contact_id in members: contact = bot.rpc.get_contact(accid, contact_id) bot.logger.info(f"Member: {contact.address}") ``` -------------------------------- ### Check Account Configuration Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/rpc-methods.md Verifies if a specific account is fully configured and ready for use. This is crucial before attempting to send or receive messages. ```python def is_configured(accid: int) -> bool: pass ``` ```python for accid in bot.rpc.get_all_account_ids(): if bot.rpc.is_configured(accid): bot.logger.info(f"Account {accid} is ready") else: bot.logger.warning(f"Account {accid} needs configuration") ``` -------------------------------- ### BotCli Initialization Without Default Commands Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/configuration.md Initialize the BotCli disabling the automatic addition of default subcommands and generic CLI options. ```python # Without default subcommands cli = BotCli("mybot", add_defaults=False) ``` -------------------------------- ### Delete Message After Processing Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/event-handling.md Uses the `@cli.after` decorator to execute a function after a `NewMessage` event has been processed. This example demonstrates deleting the processed message from the chat. ```python @cli.after(events.NewMessage) def delete_after_processing(bot, accid, event): msg = event.msg # Clean up by deleting the processed message bot.rpc.delete_messages(accid, [msg.id]) ``` -------------------------------- ### Registering Post-Event Handler with @cli.after() Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/event-handling.md Use the @cli.after() decorator to register a handler that executes after other handlers for the same event. This example logs completion of message processing. ```python @cli.after(events.NewMessage) def cleanup_after_message(bot, accid, event): # Runs after on() handlers msg = event.msg bot.logger.info(f"Finished processing message {msg.id}") ``` -------------------------------- ### Update ConfigProgressBar with Different States Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/ConfigProgressBar.md Shows how to use set_progress to indicate different states, including errors (0), partial progress, and full completion (1000). ```python pbar = ConfigProgressBar() pbar.set_progress(0) # Error state pbar.set_progress(100) # 10% complete pbar.set_progress(500) # 50% complete pbar.set_progress(1000) # 100% complete pbar.close() ``` -------------------------------- ### Get Next Event Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/rpc-methods.md Retrieves the next event from the event queue. This method is typically used internally by the event loop and is called within `bot.run_forever()`. ```python def get_next_event() -> RawEvent ``` -------------------------------- ### Define _init_parser Method Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli-internal-methods.md This internal method initializes the argument parser with default subcommands and options. It calls _add_default_generic_options and registers subcommands like 'init', 'config', 'import', 'export', 'serve', 'link', 'admin', 'list', and 'remove'. ```python def _init_parser(self) -> None: pass ``` -------------------------------- ### Handling New Message Events Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/event-handling.md Register a handler for NewMessage events to process incoming messages. This example logs the sender ID and text of any new message. ```python @cli.on(events.NewMessage) def handle_any_message(bot, accid, event): msg = event.msg bot.logger.info(f"Got message from {msg.from_id}: {msg.text}") ``` -------------------------------- ### Internal State Variable: _init_hooks Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli-internal-methods.md A set containing initialization hooks registered via the on_init() decorator. These hooks are executed before the bot starts processing messages. ```python self._init_hooks: set[CliEventHook] ``` -------------------------------- ### Get Secure Join QR Code Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/rpc-methods.md Generate a secure join QR code for a chat or the account itself using `get_chat_securejoin_qr_code`. This returns a DCACCOUNT URI string. ```python # Bot connection QR code qr = bot.rpc.get_chat_securejoin_qr_code(accid, None) print(f"Connect to bot: {qr}") # Admin group QR code admin_chatid = cli.get_admin_chat(bot.rpc, accid) admin_qr = bot.rpc.get_chat_securejoin_qr_code(accid, admin_chatid) print(f"Join admin group: {admin_qr}") ``` -------------------------------- ### Process Specific Commands Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/event-handling.md Handles specific commands like /help and /start by sending predefined responses. It also includes a default handler for non-command messages. ```python @cli.on(events.NewMessage(command="/help")) def help_cmd(bot, accid, event): msg = event.msg help_text = "Available commands: /help, /start, /stop" bot.rpc.send_msg(accid, msg.chat_id, MsgData(text=help_text)) ``` ```python @cli.on(events.NewMessage(command="/start")) def start_cmd(bot, accid, event): msg = event.msg bot.rpc.send_msg(accid, msg.chat_id, MsgData(text="Bot started")) ``` ```python @cli.on(events.NewMessage) def default_handler(bot, accid, event): # Only process if not a command if bot.has_command(event.command): return msg = event.msg bot.logger.info(f"Regular message: {msg.text}") ``` -------------------------------- ### Conditional Message Handling Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/event-handling.md Route incoming messages to different handler functions based on their content or type. This example checks if a message is a command, a file, or regular text. ```python @cli.on(events.NewMessage) def smart_router(bot, accid, event): msg = event.msg if msg.text.startswith("/"): # It's a command handle_command(bot, accid, event) elif msg.file: # It's a file handle_file(bot, accid, event) else: # Regular text handle_text(bot, accid, event) ``` -------------------------------- ### Set Bot Configuration for Specific Account Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/subcommands.md Configure a specific setting for a particular account by using the --account option along with the configuration key and value. ```bash ./mybot config --account 1 selfstatus "I'm online" ``` -------------------------------- ### Multiple Event Handlers Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/event-handling.md All registered handlers for a specific event will be called sequentially, even if one of them raises an exception. This example shows three handlers for the NewMessage event. ```python @cli.on(events.NewMessage) def handler_1(bot, accid, event): bot.logger.info("Handler 1") @cli.on(events.NewMessage) def handler_2(bot, accid, event): bot.logger.info("Handler 2") @cli.on(events.NewMessage) def handler_3(bot, accid, event): bot.logger.info("Handler 3") # All three will run when NewMessage occurs ``` -------------------------------- ### Import Account Backup Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/rpc-methods.md Imports an account from a backup file. Requires the account ID, path to the backup file, and optionally a passphrase. Handle potential import errors. ```python try: bot.rpc.import_backup(accid, "/path/to/backup.tar", None) except JsonRpcError as e: bot.logger.error(f"Import failed: {e}") ``` -------------------------------- ### Internal State Variable: _add_defaults Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli-internal-methods.md A boolean flag that determines whether default subcommands and options are added to the parser. Its value is set during initialization and checked in the start() method. ```python self._add_defaults: bool ``` -------------------------------- ### Get Contact Information Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/rpc-methods.md Retrieves detailed information about a specific contact using their account and contact IDs. Useful for displaying contact details or checking contact properties. ```python def get_contact(accid: int, contact_id: int) -> Contact ``` ```python contact = bot.rpc.get_contact(accid, msg.from_id) bot.logger.info(f"From: {contact.display_name} ({contact.address})") ``` -------------------------------- ### Get Bot Admin Chat ID Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli.md Fetches the administration group chat ID for a given account. Returns 0 if not configured. Resets invalid admin chats. ```python def get_admin_chat(self, rpc: Rpc, accid: int) -> int: # ... implementation details ... pass # Example usage: admin_chat_id = cli.get_admin_chat(bot.rpc, accid) if admin_chat_id > 0: bot.rpc.send_msg(accid, admin_chat_id, MsgData(text="Admin notification")) ``` -------------------------------- ### Execute Subcommand Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli-internal-methods.md Executes the selected subcommand after parsing arguments. If no subcommand is provided, it displays the help message. ```python if "cmd" in args: args.cmd(self, self._bot, args) else: self._parser.parse_args(["-h"]) ``` -------------------------------- ### import_backup Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/rpc-methods.md Imports an account from a backup file. Requires the account ID to import into, the path to the backup file, and an optional passphrase. ```APIDOC ## import_backup ### Description Import an account from a backup file. ### Method `import_backup(accid: int, path: str, passphrase: str | None) -> None` ### Parameters #### Path Parameters - **accid** (int) - Required - Account ID to import into - **path** (str) - Required - Path to backup file - **passphrase** (str | None) - Optional - Backup passphrase (usually None) ### Throws - `JsonRpcError` if import fails ### Request Example ```python try: bot.rpc.import_backup(accid, "/path/to/backup.tar", None) except JsonRpcError as e: bot.logger.error(f"Import failed: {e}") ``` ``` -------------------------------- ### Non-Blocking Event Handler with Threading Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/event-handling.md Use threading for long-running operations to prevent blocking the main event loop. This example demonstrates how to run a slow task in a separate thread. ```python import threading @cli.on(events.NewMessage) def fast_handler(bot, accid, event): def slow_task(): time.sleep(5) bot.rpc.send_msg(accid, event.msg.chat_id, MsgData(text="Done")) thread = threading.Thread(target=slow_task, daemon=True) thread.start() ``` -------------------------------- ### Blocking Event Handler Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/event-handling.md Avoid using time.sleep() or other blocking operations directly in event handlers as they will block all other event processing. This example shows a slow handler that blocks other messages. ```python # SLOW - blocks other messages @cli.on(events.NewMessage) def slow_handler(bot, accid, event): time.sleep(5) # 5 second delay blocks all events bot.rpc.send_msg(accid, event.msg.chat_id, MsgData(text="Done")) ``` -------------------------------- ### on_init Callback Signature Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/api-reference/BotCli-internal-methods.md This is the expected signature for callbacks registered with the on_init hook. It receives the bot instance and parsed arguments. ```python def callback(bot: Bot, args: Namespace) -> None ``` -------------------------------- ### Deltabot-CLI Data Flow Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/project-overview.md Illustrates the sequence of operations from user CLI execution to event handling within the deltabot-cli framework. ```text User runs CLI ArgumentParser processes arguments BotCli.start() selected subcommand function IOTransport + Rpc initialized Bot instance created with event hooks on_init hooks called Subcommand executes (init/serve/config/etc.) If serve: on_start hooks called → event loop runs Event handlers triggered on messages/events bot.rpc methods call Delta Chat core ``` -------------------------------- ### List Bot Accounts and Email Addresses Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/subcommands.md Displays all configured bot accounts along with their associated email addresses. This helps in managing and verifying bot account configurations. ```bash ./mybot list # Output: # #1 - user@example.com # #2 - bot@example.org ``` -------------------------------- ### Get Chat Information Source: https://github.com/deltachat-bot/deltabot-cli-py/blob/master/_autodocs/rpc-methods.md Retrieve detailed information about a specific chat using `get_chat`. The returned `Chat` object contains properties like name, kind, and protection status. ```python chat = bot.rpc.get_chat(accid, chatid) bot.logger.info(f"Chat: {chat.name} (type: {chat.kind})") ```