Metadata-Version: 2.4
Name: webex-bot-core
Version: 3.1.2
Summary: Webex bot framework with RBAC, an interactive scheduler and Adaptive Card support
Author-email: Lei Zhang <liozza@163.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/liozzazhang/webex-bot-core
Project-URL: Source, https://github.com/liozzazhang/webex-bot-core
Project-URL: Issues, https://github.com/liozzazhang/webex-bot-core/issues
Keywords: webex,bot,chatops,adaptive-cards,rbac,scheduler
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Communications :: Chat
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: APScheduler~=3.11.0
Requires-Dist: backoff>=2.2.1
Requires-Dist: certifi>=2024.7.4
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: PyYAML>=6.0.1
Requires-Dist: requests>=2.32.3
Requires-Dist: webexpythonsdk>=2.0.5
Requires-Dist: websockets>=11.0.3
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Dynamic: license-file

# webex-bot-core

A Webex Bot framework for rapid bot development with built-in RBAC, interactive scheduler, and Adaptive Card support.



- [webex-bot-core](#webex-bot-core)
  - [Installation](#installation)
    - [Prerequisite](#prerequisite)
    - [Install](#install)
  - [Quick Start](#quick-start)
  - [Configuration](#configuration)
    - [config.yml](#configyml)
    - [Authentication and RBAC](#authentication-and-rbac)
    - [Commands](#commands)
    - [Scheduler](#scheduler)
  - [Developing Commands](#developing-commands)
    - [Project Structure](#project-structure)
    - [Single Command](#single-command)
    - [Card Command](#card-command)
  - [Scheduler System](#scheduler-system)
    - [Overview](#overview)
    - [Job Types](#job-types)
    - [Admin Interface](#admin-interface)
    - [User Interface](#user-interface)
  - [Release Notes](#release-notes)
  - [Reference](#reference)
  - [Support](#support)
  - [License](#license)



## Installation

### Prerequisite

- Python >= 3.10
- A Webex bot access token — create a bot at
  [developer.webex.com](https://developer.webex.com/my-apps/new/bot)

### Install

```shell
pip install webex-bot-core

bot-toolkit -v
webex_bot_core v3.1.2
```

From a checkout:

```shell
make dev     # .venv + editable install with dev extras
make test
```

## Quick Start

1. Create a `config.yml` (see [Configuration](#configuration))
2. Create your command files in a `commands/` directory
3. Run the bot:

```shell
bot-toolkit -c config.yml
```

## Configuration

### config.yml

```yaml
# bot section
bot:
  name: "Webex Bot Core"
  token: ""
  command_home: commands
  callback_room: ""

# authentication and RBAC
auth:
  domain:
    - example.com
  roles:
    admin:
      emails:
        - admin@example.com
      patterns:
        - "*-admin@example.com"
  default_role: user

# command switch — supports bool (legacy) or dict with enabled + roles
commands:
  single_command:
    enabled: true
    roles: [user]
  card_command:
    enabled: true
    roles: [operator, admin]

# scheduler
scheduler:
  enabled: true
  db_path: "data/scheduler.db"
  seed_jobs:
    - type: command
      command: single_command
      schedule: "0 9 * * 1"
      target_user_email:
        - user@example.com

# logging level: DEBUG, INFO, WARNING, ERROR
logging:
  level: INFO

# help card
help:
  card_image_url: "https://example.com/image.jpg"
  subtitle: "Bot Help Message"
```

### Authentication and RBAC

The auth module provides domain-based allowlisting and role-based access control.

**Domain allowlist** — only users from listed domains can interact with the bot:

```yaml
auth:
  domain:
    - example.com
```

**Roles** — define named roles with explicit email members and wildcard patterns:

```yaml
auth:
  roles:
    admin:
      emails:
        - admin@example.com
      patterns:
        - "*-admin@example.com"
    operator:
      emails: []
      patterns:
        - "*-ops@example.com"
  default_role: user   # all domain-approved users get this role
```

Role resolution: every authenticated user receives `default_role` automatically. Additional roles are granted if the user's email matches any entry in `emails` or `patterns` (glob-style matching).

### Commands

Commands can be enabled/disabled and optionally bound to RBAC roles:

```yaml
# Extended format (recommended)
commands:
  single_command:
    enabled: true
    roles: [user]           # accessible by all authenticated users
  card_command:
    enabled: true
    roles: [admin]          # restricted to admin role

# Legacy format (still supported)
commands:
  single_command: true      # equivalent to enabled: true, roles: [default_role]
```

### Scheduler

The scheduler replaces the old `plugins.cronjob` with a SQLite-backed system supporting four job types, interactive Adaptive Card management, and per-user data.

```yaml
scheduler:
  enabled: true
  db_path: "data/scheduler.db"
```

When enabled, two built-in commands are registered:

- `scheduler admin` — admin panel (requires `admin` role)
- `scheduler` — user panel (all authenticated users)

## Developing Commands

### Project Structure

```
my-bot/
├── cards/
│   └── example.json
├── commands/
│   ├── single_command.py
│   └── card_command.py
└── config.yml
```

- `cards/` — Adaptive Card JSON files
- `commands/` — command modules (configurable via `bot.command_home`)
- `config.yml` — bot configuration

### Single Command

```python
from webex_bot_core.commands.base import BaseCommandInterface
from webex_bot_core.utils.formatting import quote_info


class BaseCommand(BaseCommandInterface):
    NAME = "single_command"
    HELP_MESSAGE = "Single Command"

    def __init__(self, configs, raise_exception=False, notification=None):
        super().__init__(configs, raise_exception=raise_exception, notification=notification)

    def execute(self, message, attachment_actions, activity):
        self._log.info("Start to execute")
        self._notification.send_notification(f"message: {message}")
        self._notification.callback("Example callback to admin space")
        return "This is an example of how to develop a module."

    def pre(self, message, attachment_actions, activity, **kwargs):
        super().pre(message, attachment_actions, activity, **kwargs)
        return quote_info("This is an example of pre-executing.")
```

Key points:

- Must inherit from `BaseCommandInterface` and be named `BaseCommand`
- `NAME` — the command keyword users type to trigger it
- `HELP_MESSAGE` — shown in the help card
- `pre()` — called before `execute()`, must call `super().pre(...)` first
- `execute()` — main logic, return a string, `Response`, or list
- `self._notification` — send messages, callbacks, and threaded replies
- `self._configs` — access to all `config.yml` values

### Card Command

```python
import json

from webexpythonsdk.models.cards import (
    Colors, TextBlock, FontWeight, FontSize, Column, AdaptiveCard,
    ColumnSet, Choice, ChoiceSet,
)
from webexpythonsdk.models.cards.actions import Submit

from webex_bot_core.commands.base import BaseCommandInterface
from webex_bot_core.models.response import Response, response_from_adaptive_card


class BaseCommand(BaseCommandInterface):
    NAME = "card_command"
    HELP_MESSAGE = "Card Command"

    def __init__(self, configs):
        super().__init__(configs)
        self.chained_commands.append(CardCallbackEx1(configs))

    def execute(self, message, attachment_actions, activity):
        response = Response()
        response.text = self.NAME

        with open("cards/example.json", "r", encoding="utf-8") as f:
            example_card = json.load(f)

        actions = [
            {
                "type": "Action.Submit",
                "title": "action 1",
                "data": {
                    "callback_keyword": "callback_1",
                    "thread_parent_id": self._notification.get_parent_id(),
                },
            },
        ]
        example_card["body"].append({"type": "ActionSet", "actions": actions})

        response.add_attachment({
            "contentType": "application/vnd.microsoft.card.adaptive",
            "content": example_card,
        })
        return response

    def pre(self, message, attachment_actions, activity, **kwargs):
        super().pre(message, attachment_actions, activity, **kwargs)
        return f"{self.NAME} pre execute"


class CardCallbackEx1(BaseCommandInterface):
    CALLBACK_KEYWORD = "callback_1"
    NAME = "card_command callback1"

    def __init__(self, configs):
        super().__init__(configs, delete_previous_message=False)

    def execute(self, message, attachment_actions, activity):
        return "callback1 execute success"
```

Key points:

- Use `chained_commands` to register card callback handlers
- Set `CALLBACK_KEYWORD` on callback classes (matched when card buttons are clicked)
- Always pass `thread_parent_id` in card action data to maintain threading
- Use `response_from_adaptive_card()` for SDK card objects, or build raw JSON with `Response.add_attachment()`

## Scheduler System

### Overview

The scheduler provides persistent, SQLite-backed job scheduling with interactive Adaptive Card management for both admins and users.

Architecture:

- **JobStore** (`scheduler/store.py`) — SQLite persistence for jobs and subscriptions
- **SchedulerEngine** (`scheduler/engine.py`) — APScheduler wrapper with live job management
- **Job executors** (`scheduler/jobs/`) — type-specific execution logic
- **Admin/User commands** (`commands/scheduler/`) — card-based CRUD interfaces

### Job Types


| Type        | Description                               | Targets                           |
| ----------- | ----------------------------------------- | --------------------------------- |
| `command`   | Execute a bot command on schedule         | Static: emails + rooms            |
| `script`    | Run a bash script on the host             | Static: emails + rooms            |
| `remind`    | Send a message (markdown, table, or card) | Static: emails + rooms            |
| `subscribe` | Execute a command, deliver to subscribers | Dynamic: from subscriptions table |


### Admin Interface

Trigger: type `scheduler admin` or click from help card.

The admin panel allows:

- Creating any job type (command, script, remind, subscribe service)
- Viewing all jobs across all users with status
- Enabling / disabling / deleting jobs
- Viewing subscribers for subscribe-type services

Script jobs can only be created by users with the `admin` role.

### User Interface

Trigger: type `scheduler` or click from help card.

The user panel allows:

- Viewing and managing own jobs (create, enable/disable, delete)
- Creating command, script, or remind jobs
- Browsing available subscription services
- Subscribing / unsubscribing from services
- Viewing active subscriptions

## Release Notes

- v3.1.2
  - Shared helpers live in one module, `webex_bot_core.utils.common_libs`:
    `SuperDict` (dotted-key config access), `yaml_file_concurrent_operation`,
    `check_file_validation`, `load_module`, `ArgsUtil`, `LogInitializer`, and
    the `CommonLibsError` hierarchy that `BotException` and
    `BotConfigException` derive from.  Standard library and PyYAML only.
  - Removed `load_yaml` and `dotted_get` from `webex_bot_core.utils.common`
    (added in 3.1.1); use `yaml_file_concurrent_operation` and `SuperDict`.
- v3.1.1 — first public release on PyPI
  - No dependencies outside PyPI.
  - Dropped the unused `coloredlogs` dependency.
  - Packaging moved to `pyproject.toml`; `bot-toolkit` is the only installed
    entry point.
  - Mercury activity redeliveries are de-duplicated for both messages and card
    actions (`bot.activity_dedupe_seconds`, default 120).
  - Optional `.env` file support for local environment variables.
- v3.0.2
  - **Security fix — RBAC propagation to chained sub-commands.**
    The loader only assigned the configured `roles` list to the top-level
    command instance, so card-callback handlers appended to
    `self.chained_commands` (the typical place for "Submit" handlers behind
    Adaptive Cards) silently bypassed the role gate.  When an admin posted
    an admin-only card in a multi-user space, any room member could click
    the card's Submit action and the dispatcher would skip the RBAC check
    because the sub-command's `required_roles` was still `None`.
    `BotCore` now recursively propagates `required_roles` to every chained
    sub-command (including nested chains) while preserving stricter
    overrides set explicitly inside a sub-command's `__init__`.  No bot
    code changes are required — sub-commands automatically inherit the
    parent's role gate.
- v3.0.1
  - Fix `AttributeError: 'InvalidStatus' object has no attribute 'status'`
    raised on Mercury WebSocket handshake 404 (stale WDM device).
    `websockets >= 12` moved the status onto `exc.response.status_code`;
    the 404 recovery path now probes both the new and the legacy attribute
    layouts, so bots on `websockets` 9–16 all recover the same way and
    transparently re-register the device instead of crashing.
- v3.0.0 — webex-bot-v2 rewrite
  - Removed upstream `webex_bot` dependency; standalone WebSocket transport
  - Migrated to `webexpythonsdk` (Python >= 3.10)
  - Added RBAC auth module with role definitions, email patterns, and per-command role binding
  - Replaced cronjob plugin with full scheduler system (SQLite, 4 job types, interactive card UI)
  - Redesigned help card with rich Adaptive Card layout
  - Configurable logging level via `config.yml`
  - Consistent message threading for card actions and text commands
- v2.0.0
  - Renamed callback to utils
  - Moved utils.py to utils/common.py
  - Added plugins/ library
  - Added cronjob plugin
- v1.2.0
  - Added person_email target support in notification
  - Added traceback

## Reference

- [Webex Bot Python SDK](https://github.com/WebexCommunity/WebexPythonSDK)
- [Adaptive Cards Designer](https://adaptivecards.io/designer/)

## Support

- Issues and pull requests: https://github.com/liozzazhang/webex-bot-core/issues

## License

[Apache License 2.0](LICENSE).

This is an independent community project, not an official Webex product.

