amctl-template-ambot-plugin 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: ["**"]
6
+ pull_request:
7
+
8
+ jobs:
9
+ python:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: astral-sh/setup-uv@v5
14
+ - name: Install dependencies
15
+ run: uv sync
16
+ - name: Lint
17
+ uses: astral-sh/ruff-action@v3
18
+ with:
19
+ args: check . --exit-non-zero-on-fix
20
+ - name: Type check
21
+ run: uv run pyright
22
+ - name: Build package
23
+ run: uv build
24
+
25
+ frontend:
26
+ runs-on: ubuntu-latest
27
+ steps:
28
+ - uses: actions/checkout@v4
29
+ - uses: oven-sh/setup-bun@v2
30
+ with:
31
+ bun-version: latest
32
+ - name: Install dependencies
33
+ working-directory: frontend
34
+ run: bun install
35
+ - name: Type check
36
+ working-directory: frontend
37
+ run: bun run typecheck
38
+ - name: Build page
39
+ working-directory: frontend
40
+ run: bun run build
41
+ - name: Upload built page
42
+ uses: actions/upload-artifact@v4
43
+ with:
44
+ name: webui-assets
45
+ path: "**/assets/index.js"
46
+ if-no-files-found: error
@@ -0,0 +1,29 @@
1
+ name: Publish to PyPI on Release
2
+
3
+ on:
4
+ release:
5
+ types: [created]
6
+
7
+ jobs:
8
+ release:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+
13
+ # 产物随 wheel 分发,必须在 uv build 之前构建
14
+ - uses: oven-sh/setup-bun@v2
15
+ with:
16
+ bun-version: latest
17
+ - name: Build WebUI page
18
+ working-directory: frontend
19
+ run: |
20
+ bun install
21
+ bun run build
22
+
23
+ - uses: astral-sh/setup-uv@v5
24
+ - name: Install Python
25
+ run: uv python install
26
+ - name: Build and publish
27
+ run: |
28
+ uv build
29
+ uv publish --token ${{ secrets.PYPI_API_TOKEN }}
@@ -0,0 +1,21 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .venv/
6
+ .env
7
+ .python-version
8
+
9
+ # 前端
10
+ frontend/node_modules/
11
+
12
+ # 前端产物由 CI 在发布前构建,不进版本库
13
+ {{ module }}/assets/*
14
+ !{{ module }}/assets/.gitkeep
15
+
16
+ # 工具缓存
17
+ .ruff_cache/
18
+ .mypy_cache/
19
+ .pytest_cache/
20
+ dist/
21
+ build/
@@ -0,0 +1,76 @@
1
+ # {{ name }}
2
+
3
+ {{ description }}
4
+
5
+ 由 amctl 的 ambot_plugin 模板生成,带一个可挂进 AmritaBot WebUI 侧边栏的示例页面。
6
+
7
+ ## 快速开始
8
+
9
+ ```bash
10
+ uv sync # Python 侧
11
+ cd frontend && bun install
12
+ bun run build # 产物输出到 ../{{ module }}/assets/
13
+ cd ..
14
+ uv run amrita run # 启动后打开 WebUI,侧边栏即可看到页面
15
+ ```
16
+
17
+ 前端改完重新 `bun run build` 再刷新页面即可:宿主按产物 mtime 拼版本参数,
18
+ 不需要重启 bot。
19
+
20
+ ## 目录结构
21
+
22
+ ```
23
+ {{ module }}/
24
+ ├── __init__.py # 插件元信息,import 即完成路由与页面注册
25
+ ├── config.py # 配置项(页面标题、分组)
26
+ ├── api.py # JSON 接口,注册在 /api/{{ asset }}
27
+ ├── webui.py # 挂载前端产物 + 注册侧边栏页面
28
+ └── assets/ # 构建产物(index.js / index.css),随包分发
29
+ frontend/
30
+ ├── amrita-plugin.json # 构建器配置:入口、产物目录、静态资源
31
+ └── src/
32
+ ├── index.tsx # 页面组件,默认导出
33
+ └── index.css # 自带样式,运行期通过 injectCss 注入
34
+ ```
35
+
36
+ ## 页面是怎么被加载的
37
+
38
+ `webui.py` 在 import 期做两件事:
39
+
40
+ 1. `mount_plugin_assets("{{ asset }}", assets/)` 把产物目录挂到 `/plugin-assets/{{ asset }}/`
41
+ 2. `register_page(..., module_dir="{{ asset }}")` 登记侧边栏与路由
42
+ (`path="/{{ asset }}"`,访问时宿主拼出 `index.js?v=<mtime>` 并 `import()`)
43
+
44
+ 两步都必须早于 `driver.on_startup` 的 catch-all 路由,所以只能写在 import 期。
45
+ 产物缺失时只打告警,页面会显示宿主的「产物不可用」提示,不会阻断插件加载。
46
+
47
+ ## 前端约定
48
+
49
+ - 页面默认导出 React 组件;Router、QueryClient、主题由宿主负责
50
+ - `react` / `react-dom` / `react-router-dom` / `lucide-react` 等由宿主通过
51
+ `window.__AMRITA_HOST__` 提供,构建器 `@amrita-constant/webui-plugin-kit`
52
+ 会把它们换成再导出模块,插件里不会打进第二份 React
53
+ - UI 组件从这个套件的 `/ui` 入口导入,运行期同样走 `window.__AMRITA_HOST__.UI`,
54
+ 类型来自 `@amrita-constant/ambot-ui`
55
+ - 数据请求用套件 `/runtime` 的 `pluginApi`,401 会交给宿主退回登录页
56
+ - 样式请自带(`injectCss`):宿主只生成自己源码里用过的 Tailwind 类,
57
+ 插件里写 `bg-fuchsia-700` 这种冷门类会静默失效
58
+
59
+ 产物末尾会自动带 `export const amritaHostContract = 3`,宿主加载时比对契约版本。
60
+
61
+ ## 改点什么
62
+
63
+ - 换页面标题/分组:`{{ module }}/config.py`
64
+ - 加接口:在 `api.py` 里加路由,前端用 `/api/{{ asset }}/...` 请求
65
+ - 换图标:`webui.py` 里的 `icon`,取 lucide 图标名
66
+ - 加图片等静态资源:放进 `frontend/src/`,在 `amrita-plugin.json` 的 `assets` 里登记
67
+
68
+ ## 打包发布
69
+
70
+ `uv build` 会把 `{{ module }}/assets/` 一起打进 wheel。仓库自带的 publish workflow
71
+ 已经按顺序做了前端构建 → uv build → uv publish,不要再手动跳过第一步。
72
+
73
+ ## 要求
74
+
75
+ - AmritaBot >= {{ version }}(提供 `mount_plugin_assets` 与 `module_dir`)
76
+ - 开发前端需要 bun;部署机不需要 Node,产物在包里
@@ -0,0 +1,57 @@
1
+ """AmritaBot 插件模板(含 WebUI 页面与前端构建链)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from datetime import datetime, timezone
7
+ from typing import Any, ClassVar
8
+
9
+ from amctl.templating import BaseTemplate, TmplField, field
10
+
11
+ __template_ignore__ = False
12
+
13
+
14
+ def _slug(name: str) -> str:
15
+ """把项目名规整成可用的包名后缀:只留字母数字,其余折成下划线。"""
16
+ cleaned = re.sub(r"[^0-9A-Za-z]+", "_", name).strip("_").lower()
17
+ return cleaned or "demo"
18
+
19
+
20
+ class ambotPluginTemplate(BaseTemplate):
21
+ """生成可直接 `uv sync` 的 AmritaBot 插件工程。
22
+
23
+ Python 侧提供带 WebUI 页面的插件骨架(路由 + 侧边栏页面 + 产物挂载),
24
+ frontend/ 提供 React 页面与构建脚本,产物落在插件包内随包分发。
25
+ """
26
+
27
+ __template_name__: str = "ambot_plugin"
28
+ __template_description__ = "AmritaBot 插件工程:WebUI 页面 + 前端构建 + 打包发布"
29
+ # 依赖的 AmritaBot 需要自带插件产物挂载能力(mount_plugin_assets / module_dir)
30
+ __versions__: tuple[str, ...] = ("1.18.0",)
31
+ __tmpl_fields__: ClassVar[dict[str, TmplField]] = {
32
+ "description": field(
33
+ default="我的第一个 AmritaBot 插件",
34
+ description="插件简介,写入 pyproject 与 README",
35
+ ),
36
+ }
37
+
38
+ def _build_context(
39
+ self, name: str, version: str | None, **fields: Any
40
+ ) -> dict[str, Any]:
41
+ ctx = super()._build_context(name, version, **fields)
42
+ slug = _slug(name)
43
+ ctx.update(
44
+ {
45
+ # 发行名用连字符,导入名用下划线,两者都由项目名派生
46
+ "dist": f"amrita-plugin-{slug.replace('_', '-')}",
47
+ "module": f"amrita_plugin_{slug}",
48
+ # 同时是 /plugin-assets/<name>/ 的挂载名与页面路径
49
+ "asset": slug,
50
+ "page_title": name,
51
+ "created_at": datetime.now(timezone.utc).isoformat(),
52
+ }
53
+ )
54
+ return ctx
55
+
56
+
57
+ __template_export__ = ambotPluginTemplate
@@ -0,0 +1,5 @@
1
+ {
2
+ "entry": "src/index.tsx",
3
+ "outdir": "../{{ module }}/assets",
4
+ "assets": ["src/index.css"]
5
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "{{ asset }}-webui",
3
+ "private": true,
4
+ "type": "module",
5
+ "description": "{{ name }} 的 WebUI 页面",
6
+ "scripts": {
7
+ "build": "amrita-plugin-build",
8
+ "typecheck": "tsc --noEmit"
9
+ },
10
+ "devDependencies": {
11
+ "@amrita-constant/ambot-ui": "^0.1.1",
12
+ "@amrita-constant/webui-plugin-kit": "^0.1.1",
13
+ "@tanstack/react-query": "^5.101.4",
14
+ "@types/react": "^19.2.0",
15
+ "@types/react-dom": "^19.2.0",
16
+ "lucide-react": "^0.545.0",
17
+ "react": "^19.2.0",
18
+ "react-dom": "^19.2.0",
19
+ "react-router-dom": "^7.18.2",
20
+ "typescript": "^5"
21
+ }
22
+ }
@@ -0,0 +1,59 @@
1
+ /* 页面自带样式:只影响本插件,不用跟着宿主的 Tailwind 配置走 */
2
+ .{{ asset }}-page {
3
+ display: flex;
4
+ flex-direction: column;
5
+ gap: 16px;
6
+ }
7
+
8
+ .{{ asset }}-row {
9
+ display: flex;
10
+ flex-wrap: wrap;
11
+ gap: 8px;
12
+ margin-bottom: 16px;
13
+ }
14
+
15
+ .{{ asset }}-list {
16
+ display: flex;
17
+ flex-direction: column;
18
+ gap: 8px;
19
+ margin: 0;
20
+ padding: 0;
21
+ list-style: none;
22
+ }
23
+
24
+ .{{ asset }}-item {
25
+ display: flex;
26
+ align-items: center;
27
+ justify-content: space-between;
28
+ gap: 12px;
29
+ padding: 10px 12px;
30
+ border: 1px solid rgba(128, 128, 128, 0.25);
31
+ border-radius: 10px;
32
+ font-size: 14px;
33
+ }
34
+
35
+ .{{ asset }}-item small {
36
+ opacity: 0.6;
37
+ font-variant-numeric: tabular-nums;
38
+ }
39
+
40
+ .{{ asset }}-empty {
41
+ padding: 12px 0;
42
+ opacity: 0.6;
43
+ font-size: 13px;
44
+ }
45
+
46
+ .{{ asset }}-error {
47
+ margin: 0 0 12px;
48
+ color: #d94a4a;
49
+ font-size: 13px;
50
+ }
51
+
52
+ .{{ asset }}-meta {
53
+ display: flex;
54
+ align-items: center;
55
+ gap: 6px;
56
+ margin: 16px 0 0;
57
+ font-size: 13px;
58
+ opacity: 0.8;
59
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * 示例页面。宿主在运行期 `import()` 本模块并取 default 渲染,
3
+ * React、Router、QueryClient、UI 组件都由宿主提供,这里只写业务。
4
+ */
5
+ import { useCallback, useEffect, useState } from "react";
6
+ import { Plus, RefreshCw } from "lucide-react";
7
+ import {
8
+ Badge,
9
+ Button,
10
+ Card,
11
+ CardContent,
12
+ CardDescription,
13
+ CardHeader,
14
+ CardTitle,
15
+ Input,
16
+ } from "@amrita-constant/webui-plugin-kit/ui";
17
+ import { injectCss, pluginApi } from "@amrita-constant/webui-plugin-kit/runtime";
18
+
19
+ // 自带样式:宿主只生成自己源码里用过的 Tailwind 类,插件写冷门类会静默失效
20
+ injectCss(new URL("./index.css", import.meta.url).href, "{{ asset }}-style");
21
+
22
+ interface Item {
23
+ id: number;
24
+ text: string;
25
+ created_at: string;
26
+ }
27
+
28
+ export default function Page() {
29
+ const [items, setItems] = useState<Item[]>([]);
30
+ const [text, setText] = useState("");
31
+ const [error, setError] = useState("");
32
+ const [busy, setBusy] = useState(false);
33
+
34
+ const reload = useCallback(async () => {
35
+ try {
36
+ const data = await pluginApi.get<{ items: Item[]; total: number }>(
37
+ "/api/{{ asset }}/items",
38
+ );
39
+ setItems(data.items);
40
+ setError("");
41
+ } catch (err) {
42
+ setError(err instanceof Error ? err.message : String(err));
43
+ }
44
+ }, []);
45
+
46
+ useEffect(() => {
47
+ void reload();
48
+ }, [reload]);
49
+
50
+ const submit = async () => {
51
+ const value = text.trim();
52
+ if (!value || busy) return;
53
+ setBusy(true);
54
+ try {
55
+ await pluginApi.post("/api/{{ asset }}/items", { text: value });
56
+ setText("");
57
+ await reload();
58
+ } catch (err) {
59
+ setError(err instanceof Error ? err.message : String(err));
60
+ } finally {
61
+ setBusy(false);
62
+ }
63
+ };
64
+
65
+ return (
66
+ <div className="{{ asset }}-page">
67
+ <Card>
68
+ <CardHeader>
69
+ <CardTitle>{{ page_title }}</CardTitle>
70
+ <CardDescription>
71
+ 模板自带的示例页面:数据接口在 /api/{{ asset }},产物在 /plugin-assets/{{ asset }}/。
72
+ </CardDescription>
73
+ </CardHeader>
74
+ <CardContent>
75
+ <div className="{{ asset }}-row">
76
+ <Input
77
+ value={text}
78
+ placeholder="写点什么,回车提交"
79
+ onChange={(event) => setText(event.target.value)}
80
+ onKeyDown={(event) => {
81
+ if (event.key === "Enter") void submit();
82
+ }}
83
+ />
84
+ <Button onClick={() => void submit()} disabled={busy || !text.trim()}>
85
+ <Plus />
86
+ 添加
87
+ </Button>
88
+ <Button variant="outline" onClick={() => void reload()} disabled={busy}>
89
+ <RefreshCw />
90
+ 刷新
91
+ </Button>
92
+ </div>
93
+
94
+ {error ? <p className="{{ asset }}-error">{error}</p> : null}
95
+
96
+ <ul className="{{ asset }}-list">
97
+ {items.length === 0 ? (
98
+ <li className="{{ asset }}-empty">还没有记录,加一条试试。</li>
99
+ ) : (
100
+ items.map((item) => (
101
+ <li key={item.id} className="{{ asset }}-item">
102
+ <span>{item.text}</span>
103
+ <small>{item.created_at}</small>
104
+ </li>
105
+ ))
106
+ )}
107
+ </ul>
108
+
109
+ <p className="{{ asset }}-meta">
110
+ 共 <Badge variant="secondary">{items.length}</Badge> 条
111
+ </p>
112
+ </CardContent>
113
+ </Card>
114
+ </div>
115
+ );
116
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
5
+ "module": "ESNext",
6
+ "moduleResolution": "bundler",
7
+ "jsx": "react-jsx",
8
+ "strict": true,
9
+ "noEmit": true,
10
+ "skipLibCheck": true,
11
+ "esModuleInterop": true,
12
+ "forceConsistentCasingInFileNames": true
13
+ },
14
+ "include": ["src"]
15
+ }
@@ -0,0 +1,86 @@
1
+ [project]
2
+ name = "{{ dist }}"
3
+ version = "0.1.0"
4
+ description = "{{ description }}"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10, <3.14"
7
+ dependencies = [
8
+ "amrita>={{ version }}",
9
+ ]
10
+
11
+ [project.urls]
12
+ "Homepage" = "https://github.com/AmritaBot/{{ dist }}"
13
+ "Source" = "https://github.com/AmritaBot/{{ dist }}"
14
+ "Issue Tracker" = "https://github.com/AmritaBot/{{ dist }}/issues"
15
+
16
+ [tool.setuptools.packages.find]
17
+ include = ["{{ module }}*"]
18
+ namespaces = false
19
+
20
+ # 前端产物随包分发:pip 装完就有页面,不需要在部署机上装 Node
21
+ [tool.setuptools.package-data]
22
+ "{{ module }}" = ["assets/*"]
23
+
24
+ [dependency-groups]
25
+ dev = [
26
+ "ruff>=0.12.8",
27
+ "pyright>=1.1.407",
28
+ ]
29
+
30
+ [tool.uv]
31
+ package = true
32
+
33
+ [tool.ruff]
34
+ line-length = 88
35
+ target-version = "py310"
36
+
37
+ [tool.ruff.lint]
38
+ select = [
39
+ "F", # Pyflakes
40
+ "W", # pycodestyle warnings
41
+ "E", # pycodestyle errors
42
+ "UP", # pyupgrade
43
+ "ASYNC", # flake8-async
44
+ "C4", # flake8-comprehensions
45
+ "T10", # flake8-debugger
46
+ "PYI", # flake8-pyi
47
+ "PT", # flake8-pytest-style
48
+ "Q", # flake8-quotes
49
+ "RUF", # Ruff-specific rules
50
+ "I", # isort
51
+ "PERF", # pylint-performance
52
+ ]
53
+ ignore = [
54
+ "E402", # module-import-not-at-top-of-file
55
+ "E501", # line-too-long
56
+ "UP037", # quoted-annotation
57
+ "RUF001", # ambiguous-unicode-character-string
58
+ "RUF002", # ambiguous-unicode-character-docstring
59
+ "RUF003", # ambiguous-unicode-character-comment
60
+ ]
61
+
62
+ [tool.pyright]
63
+ typeCheckingMode = "standard"
64
+
65
+ [tool.nonebot]
66
+ plugins = [
67
+ "amrita.plugins.chat",
68
+ "amrita.plugins.webui",
69
+ "{{ module }}",
70
+ ]
71
+ adapters = [
72
+ { name = "OneBot V11", module_name = "nonebot.adapters.onebot.v11" },
73
+ ]
74
+
75
+ [tool.amctl.project]
76
+ project-type = "{{ project_type }}"
77
+ version = "{{ version }}"
78
+ created_at = "{{ created_at }}"
79
+
80
+ [tool.amctl.scripts]
81
+ lint = "uv run ruff check ."
82
+ sync = "uv sync"
83
+ format = "uv run ruff format ."
84
+ run = "uv run amrita run"
85
+ build = "uv build"
86
+ webui = "bun run --cwd frontend build"
@@ -0,0 +1,18 @@
1
+ """{{ description }}"""
2
+
3
+ from nonebot.plugin import PluginMetadata, require
4
+
5
+ # WebUI 的扩展点在宿主插件里:先声明依赖,再 import 自己的注册代码
6
+ require("amrita.plugins.webui")
7
+
8
+ from . import api, webui # noqa: E402 import 即注册路由与页面
9
+
10
+ __plugin_meta__ = PluginMetadata(
11
+ name="{{ name }}",
12
+ description="{{ description }}",
13
+ usage="打开 WebUI,在侧边栏找到「{{ page_title }}」页面。",
14
+ type="application",
15
+ supported_adapters={"~onebot.v11"},
16
+ )
17
+
18
+ __all__ = ["api", "webui"]
@@ -0,0 +1,55 @@
1
+ """页面用的 JSON 接口,注册在 ``/api/{{ asset }}`` 下。
2
+
3
+ 插件路由受 WebUI 登录中间件保护:未登录时 ``/api`` 前缀返回 401 JSON。
4
+ 所有响应统一走 ``ok()`` / ``fail()``,前端按 ``success`` 判断。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ from datetime import datetime
11
+ from typing import Any
12
+
13
+ from fastapi import APIRouter
14
+ from pydantic import BaseModel, Field
15
+
16
+ from amrita.plugins.webui.API import register_router
17
+ from amrita.plugins.webui.service.response import fail, ok
18
+
19
+ router = APIRouter()
20
+
21
+ # 示例数据只放内存,重启即清空;接数据库时保持接口形状不变即可
22
+ _items: list[dict[str, Any]] = []
23
+ _lock = asyncio.Lock()
24
+
25
+
26
+ class ItemIn(BaseModel):
27
+ text: str = Field(min_length=1, max_length=100)
28
+
29
+
30
+ @router.get("/items")
31
+ async def list_items() -> Any:
32
+ async with _lock:
33
+ items = list(_items)
34
+ return ok(data={"items": items, "total": len(items)})
35
+
36
+
37
+ @router.post("/items")
38
+ async def add_item(payload: ItemIn) -> Any:
39
+ text = payload.text.strip()
40
+ if not text:
41
+ return fail(400, "内容不能为空")
42
+ async with _lock:
43
+ _items.append(
44
+ {
45
+ "id": len(_items) + 1,
46
+ "text": text,
47
+ "created_at": datetime.now().isoformat(timespec="seconds"),
48
+ }
49
+ )
50
+ total = len(_items)
51
+ return ok("已添加", data={"total": total})
52
+
53
+
54
+ # 必须在 import 期注册:晚于 driver.on_startup 的 catch-all 路由会被它抢先匹配
55
+ register_router(router, prefix="/api/{{ asset }}", tags=["{{ name }}"])
@@ -0,0 +1,18 @@
1
+ """插件配置。
2
+
3
+ 字段对应 .env 里的 ``AMRITA_PLUGIN_{{ module | upper }}_<FIELD>``,
4
+ 不写就用下面的默认值。
5
+ """
6
+
7
+ from nonebot import get_plugin_config
8
+ from pydantic import BaseModel
9
+
10
+
11
+ class Config(BaseModel):
12
+ """页面在侧边栏里的显示名与分组,可按需增删。"""
13
+
14
+ page_title: str = "{{ page_title }}"
15
+ page_category: str = "其他功能"
16
+
17
+
18
+ CONFIG = get_plugin_config(Config)
@@ -0,0 +1,42 @@
1
+ """把前端产物挂到 ``/plugin-assets/{{ asset }}/`` 并注册侧边栏页面。
2
+
3
+ 这两步都只能在插件 import 期做:SPA 的 catch-all 路由挂在
4
+ ``driver.on_startup``,晚于它挂载的静态目录永远收不到请求。
5
+ """
6
+
7
+ from pathlib import Path
8
+
9
+ from nonebot import logger
10
+
11
+ from amrita.plugins.webui.API import register_page
12
+ from amrita.plugins.webui.service.plugin_assets import mount_plugin_assets
13
+
14
+ from .config import CONFIG
15
+
16
+ # 同时是挂载名、module_dir 与页面路径,宿主据此拼出产物 URL
17
+ ASSET_NAME = "{{ asset }}"
18
+ ASSET_DIR = Path(__file__).parent / "assets"
19
+
20
+
21
+ def _mount_assets() -> bool:
22
+ """产物缺失时只告警,不阻断插件加载——页面会显示宿主的「产物不可用」提示。"""
23
+ try:
24
+ mount_plugin_assets(ASSET_NAME, ASSET_DIR)
25
+ except FileNotFoundError as exc:
26
+ logger.warning(f"[{ASSET_NAME}] 前端产物不可用:{exc}")
27
+ logger.warning(
28
+ f"[{ASSET_NAME}] 执行 cd frontend && bun install && bun run build 后重启"
29
+ )
30
+ return False
31
+ return True
32
+
33
+
34
+ MOUNTED = _mount_assets()
35
+
36
+ register_page(
37
+ path=f"/{ASSET_NAME}",
38
+ page_name=CONFIG.page_title,
39
+ category=CONFIG.page_category,
40
+ icon="flask-conical",
41
+ module_dir=ASSET_NAME,
42
+ )
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: amctl-template-ambot-plugin
3
+ Version: 0.1.0
4
+ Summary: amctl template: AmritaBot plugin with a WebUI page and frontend build pipeline
5
+ Project-URL: Homepage, https://github.com/AmritaBot/amctl-template-ambot-plugin
6
+ Project-URL: Source, https://github.com/AmritaBot/amctl-template-ambot-plugin
7
+ Project-URL: Issue Tracker, https://github.com/AmritaBot/amctl-template-ambot-plugin/issues
8
+ Requires-Python: <3.15,>=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: amctl>=0.1.2
12
+ Dynamic: license-file
13
+
14
+ # amctl-template-ambot-plugin
15
+
16
+ `amctl` 模板:生成一个带 WebUI 页面、前端构建链和发布流程的 AmritaBot 插件工程。
17
+
18
+ ## 安装与使用
19
+
20
+ ```bash
21
+ uv tool install amctl --with amctl-template-ambot-plugin
22
+
23
+ amctl create -t ambot_plugin -n my-plugin
24
+ cd my-plugin
25
+ uv sync
26
+ cd frontend && bun install && bun run build && cd ..
27
+ uv run amrita run
28
+ ```
29
+
30
+ 生成后:WebUI 侧边栏出现「my-plugin」页面,页面数据走 `/api/my-plugin/items`,
31
+ 前端产物在插件包内,随 wheel 分发——部署机不需要 Node。
32
+
33
+ ## 生成什么
34
+
35
+ ```
36
+ my-plugin/
37
+ ├── pyproject.toml # 依赖 amrita>=1.18.0,package-data 带上产物
38
+ ├── amrita_plugin_my_plugin/
39
+ │ ├── __init__.py # PluginMetadata,import 即注册
40
+ │ ├── config.py # page_title / page_category
41
+ │ ├── api.py # /api/my-plugin/items 的 GET 与 POST
42
+ │ ├── webui.py # mount_plugin_assets + register_page(module_dir=...)
43
+ │ └── assets/ # 构建产物,构建前不存在
44
+ ├── frontend/
45
+ │ ├── amrita-plugin.json # 入口、产物目录、静态资源
46
+ │ ├── package.json # 依赖 @amrita-constant/webui-plugin-kit
47
+ │ └── src/index.tsx # 示例页面(Card / Input / Button / Badge)
48
+ └── .github/workflows/ # push/PR 检查,release 时构建前端并发布到 PyPI
49
+ ```
50
+
51
+ 项目名会被规整成三种形态:发行名 `amrita-plugin-my-plugin`、导入名
52
+ `amrita_plugin_my_plugin`、挂载名 `my_plugin`(同时是 `/plugin-assets/<name>/`
53
+ 与页面路径 `/my_plugin`)。
54
+
55
+ ## 依赖的两个约定
56
+
57
+ - **宿主契约版本 3**:插件产物末尾带 `export const amritaHostContract = 3`,
58
+ 宿主加载时比对;React 等运行时依赖通过 `window.__AMRITA_HOST__` 注入,
59
+ 插件不打包第二份。
60
+ - **产物挂载**:`mount_plugin_assets("my_plugin", assets/)` 必须在插件 import 期调用,
61
+ 晚于 `driver.on_startup` 的 catch-all 路由就收不到请求;产物缺失时只告警,
62
+ 页面显示「产物不可用」而不阻断插件加载。
63
+
64
+ 构建器来自 [`@amrita-constant/webui-plugin-kit`](https://github.com/AmritaBot/AmritaBot-PluginKit),
65
+ UI 组件与类型来自 `@amrita-constant/ambot-ui`。
66
+
67
+ ## 开发这个模板
68
+
69
+ 模板本体是 `amctl.templ` 命名空间包,文件后缀决定处理方式:
70
+
71
+ | 后缀 | 行为 |
72
+ |---|---|
73
+ | `.tmpl` | Jinja2 渲染,输出时去掉后缀 |
74
+ | `.pre` | 原样复制,输出时去掉后缀(用于含 `${{ }}` 的 GitHub Actions 文件) |
75
+ | 其他 | 原样复制 |
76
+
77
+ 目录名 `{{ module }}` 也会被渲染。改完本地验证:
78
+
79
+ ```bash
80
+ uv build
81
+ uv pip install --force-reinstall dist/*.whl # 装进有 amctl 的环境
82
+ amctl create -t ambot_plugin -n demo-panel --frozen -o /tmp/gen
83
+ cd /tmp/gen/demo-panel/frontend && bun install && bun run typecheck && bun run build
84
+ ```
85
+
86
+ 发布:建 release 后由 workflow 用 `PYPI_API_TOKEN` 推到 PyPI。
@@ -0,0 +1,20 @@
1
+ amctl/templ/ambot_plugin/.gitignore.tmpl,sha256=pNNXFay_GvRBiKkSuttmuLvgsu7wmy6DUPZ78DN5LEU,286
2
+ amctl/templ/ambot_plugin/README.md.tmpl,sha256=2BEuPjvWE8DpdhGfJ9vDMkSbRdnisLl7QSBZCHTqxzg,3258
3
+ amctl/templ/ambot_plugin/__init__.py,sha256=wpdQxQNi63UW2vbk6w2ZdTwCuzXVJfbtdH2mCYHw1o8,2090
4
+ amctl/templ/ambot_plugin/pyproject.toml.tmpl,sha256=oTm-VUFrlw9WodBZkmwBh8eF2W25x2Q8d73dYRWRdi4,2010
5
+ amctl/templ/ambot_plugin/.github/workflows/ci.yml.pre,sha256=MGE-jyA2CT9VVNCpRRmBE8pYOWEl1iR4uE2Uk11F4-I,1090
6
+ amctl/templ/ambot_plugin/.github/workflows/publish.yml.pre,sha256=4LjUkkxN1OwZuPhy_-FD-oe6rvse_9leSmAP5LuJ00I,655
7
+ amctl/templ/ambot_plugin/frontend/amrita-plugin.json.tmpl,sha256=xv1Oq1niB4_L8byNhhNWWjgHDP_wjls7S2sRtTG4xxI,100
8
+ amctl/templ/ambot_plugin/frontend/package.json.tmpl,sha256=dCcBJnenSgkRhzyBoJQfjiSIMnW5OgrCfUaMkUKO42I,580
9
+ amctl/templ/ambot_plugin/frontend/tsconfig.json.pre,sha256=CrRo_n7a2gkZru3REvJMFhqzsosiU0V-OjhB80yonfE,346
10
+ amctl/templ/ambot_plugin/frontend/src/index.css.tmpl,sha256=TUPekEsGG0Sddw_DfPAbnaRpmdOjc_k8HHHAR9kxf4w,978
11
+ amctl/templ/ambot_plugin/frontend/src/index.tsx.tmpl,sha256=qyF0c5-iI6tge7YGIXFwDLbad0dCadfzt08z-gmtt6k,3456
12
+ amctl/templ/ambot_plugin/{{ module }}/__init__.py.tmpl,sha256=PlNpMe5M-Gzl3dAy4LU5olWasRr1f8PWQcS0I9J4h80,541
13
+ amctl/templ/ambot_plugin/{{ module }}/api.py.tmpl,sha256=pg2xzNecMf1v4j0Ph6II_8wYz01MiNn9h7OhOiQHRN8,1590
14
+ amctl/templ/ambot_plugin/{{ module }}/config.py.tmpl,sha256=Tfy4mIdaK-ZeXdethRXJm7nC7EAX3WLBdB4gJFFwIS0,423
15
+ amctl/templ/ambot_plugin/{{ module }}/webui.py.tmpl,sha256=sSNpUyEdftHF5FN6CET_Ppcfh3GMpWgFzOmjDYfo3eE,1282
16
+ amctl_template_ambot_plugin-0.1.0.dist-info/licenses/LICENSE,sha256=8VTG5ydmOOtIK16JjPynnli7NXHvwIOve0Lytaepo8Q,1071
17
+ amctl_template_ambot_plugin-0.1.0.dist-info/METADATA,sha256=ut144wyYh0Qso9tS7aKqtuZSnFf9KbFYuox78r7kDyQ,3559
18
+ amctl_template_ambot_plugin-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
19
+ amctl_template_ambot_plugin-0.1.0.dist-info/top_level.txt,sha256=cWBDbwL_v-EdEp-moCL_e3fJVbbn6JOjy_Ibd-1FxFI,6
20
+ amctl_template_ambot_plugin-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AmritaConstant
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.