magic-campus-sdk
Python SDK and CLI for MagicCampus platform integrations. IM remains a supported domain, and this repository keeps the bundled OpenIM transport inside magiccampus_sdk.
This project removes direct user-facing dependency on OpenIM token and endpoint configuration. You only configure:
apiurlapikeyplatform
At runtime, IM-backed flows call:
GET /api/v1/accounts/imToken?platform=<PLATFORM>
and uses the response fields:
userIdimTokenwsApihttpApi
Install locally
uv sync
This repository vendors only the OpenIM transport pieces that magiccampus_sdk actually uses, and layers platform-facing SDK / CLI commands on top.
IM-specific low-level internals, models, and protobufs now live under magiccampus_sdk.im.
CLI quick start
magic-campus --help
export MAGIC_CAMPUS_BASE_URL=https://campus.example.com
export MAGIC_CAMPUS_API_KEY="<api-key>"
magic-campus auth status --format pretty
magic-campus im group get --group group_123 --format pretty
magic-campus im group get-batch --groups group_123,group_456
magic-campus im notify send --to user:10134002 --text "hello"
magic-campus im notify send --to user:10134002 --markdown "# title\n\nbody"
magic-campus im notify send --to user:10134002 --custom '{"data":"{\"customType\":1}","extension":"example","description":"example custom message"}'
magic-campus im notify send --to user:10134002 --custom '{"customType":503,"data":{"title":"title","subTitle":"subTitle","schema":"https://example.com/playground"}}' --cover-image /path/to/playground.jpg
magic-campus im notify send-link-card --to user:10134002 --title "title" --sub-title "subTitle" --schema "https://example.com/playground" --cover-image /path/to/playground.jpg
magic-campus im notify send-link-card --to user:10134002 --title "title" --sub-title "subTitle" --schema "https://example.com/playground" --cover-image https://example.com/playground.jpg
magic-campus space get --group group_123 --format pretty
magic-campus space list-notice --space space_123 --format table
magic-campus space list-notice --group group_123 --format table
magic-campus space create-notice --space space_123 --title "Maintenance" --text "Starts at 22:00" --expiretime 1785510000000
magic-campus space create-notice --group group_123 --title "Maintenance" --text "Starts at 22:00" --expiretime 1785510000000
magic-campus space group update-name --group group_123 --name "New group name"
magic-campus user get --id 10134002 --format pretty
magic-campus user list --all --academy-code Nature --fields userId,nickname,email --format table
magic-campus user list --random --fields userId,nickname --format table
magic-campus user update-profile --id 10134002 --nickname "New Name" --avatar-url "https://cdn.example.com/avatar.png"
magic-campus user update-profile --id 10134002 --avatar-url "" # restore the default avatar
magic-campus user get-growth-profile --id 10134002 --format pretty
magic-campus user init-growth-profile --id 10134002 --reset false
magic-campus user set-academy --id 10134002 --academy-code Nature
magic-campus user adjust-elements --id 10134002 --metal-delta 5 --water-delta -2
send-link-card returns only ok, serverMsgID, and sendTime by default. Add --debug for the full send result.
For an HTTP(S) cover URL, the CLI reads its image dimensions and keeps that URL in the card without uploading a copy.
从 0.2.21 起,所有 CLI 业务命令只使用 MAGIC_CAMPUS_BASE_URL 和 MAGIC_CAMPUS_API_KEY。缺少任一配置即失败;旧环境变量和本地账号文件不参与业务认证。--account 仅接受 default,需要切换身份时更换运行环境中的这两个变量。--platform 可显式覆盖默认 IOS。
config init|list|use|remove 保留用于手动管理旧配置文件,但其中的凭据不再用于业务命令。现有文件不会自动迁移或删除。
space get --group <groupId> includes personGroupId, taken from the groupId field of the space returned by /agent/v1/space/getByGroupId.
The output's groupId is the ID supplied to the command. If the response has no groupId or its value is null, personGroupId is an empty string.
The output also includes the response's innerData unchanged, preserving groupId, groupType (PERSON or AGENT), groupName, and memberCount with their original value types. If innerData is absent or null, the output is null.
im notify send sends over MagicCampus HTTP POST /agent/v1/im/sendMessage. im notify history still relies on the websocket transport and local sync database.
im group get returns the group details in groupInfo; im group get-batch returns them in groupInfos.
Both commands log in using the environment credential and call POST /group/get_groups_info through the IM SDK.
Batch IDs accept a comma-separated list or a JSON array, for example --groups '["group_123","group_456"]'.
Use --group-id / --group-ids as aliases for --group / --groups, and --platform to override the default platform. --account only accepts default.
These commands query known group IDs; they do not list joined groups. A missing single group returns an error; batch results include only the groups returned by the server.
Legacy compatibility commands remain available:
magic-campus notify +send --to user:10134002 --text "hello"
magic-campus notify +history --to user:10134002
CLI config is stored at:
~/.magic-campus/auth/magiccampus-im-sdk.json
Supported commands:
config init|list|use|removeauth statusim group get --group <groupId>im group get-batch --groups <id1,id2>im notify sendim notify historyim reaction add --conversation-id <id> --server-msg-id <id> --msg-sender-id <userId> --reaction-code <code>im reaction delete --conversation-id <id> --server-msg-id <id> --msg-sender-id <userId> --reaction-id <id>space getspace list-notice (--space <spaceId> | --group <groupId>)space create-notice (--space <spaceId> | --group <groupId>)space group update-nameuser getuser list (--all | --random) [--fields <field1,field2>] [--academy-code <code>]user update-profile --id <userId> [--nickname <name>] [--avatar-url <url>]user get-growth-profile --id <userId>user init-growth-profile --id <userId> [--reset <true|false>]user set-academy --id <userId> --academy-code <Material|Digital|Sound|Movement|Nature|Healing>user adjust-elements --id <userId> [--metal-delta <int>] [--wood-delta <int>] [--water-delta <int>] [--fire-delta <int>] [--earth-delta <int>]feed list [--limit <1-100>] [--cursor <value>](真实用户 Story,按发布时间倒序)notify +send(compat)notify +history(compat)
Python SDK quick start
from magiccampus_sdk import MagicCampusConfig, MagicCampusSDK
sdk = MagicCampusSDK(
MagicCampusConfig(
apiurl="https://api-test.pearlapi.com",
apikey="YOUR_API_KEY",
platform="IOS",
)
)
space = sdk.get_space_by_group_id("GROUP_ID")
print(space.id)
print(space.name)
print(space.introduction)
查询响应与新增字段
用户资料、成长档案、空间及公告查询保留已有类型属性,并通过模型的 raw 字典保存完整响应。例如 client.user.get("USER_ID").raw.get("locale") 可读取尚未声明为类型属性的返回字段,无需逐项增加模型属性。
CLI 的 user get、user list、user get-growth-profile、space get 和 space list-notice 保留服务端新增字段,同时保持已有字段的规范化类型、默认值与别名。用户资料内的空间摘要也保留新增字段;ok、accountId、provider、resource、transport、magiccampus 等 CLI 元数据由命令决定,不允许响应覆盖。
user list 默认返回全部可用字段;--fields userId,locale 可选择任意顶层字段,不依赖固定白名单。某条记录中缺失的所选字段输出 null,因此字段拼写错误也会得到 null;空结果仍为 []。已有参数校验与认证规则保持不变。
此机制兼容新增返回字段,不自动适配字段删除、改名或类型变化。仅有类型属性提供类型提示;raw 中的扩展字段保留服务端原值,不额外验证其业务语义。
用户 Story 列表
magic-campus feed list 查询所有真实用户发布成功的 APP Story,按 createdAt DESC, id DESC 排序,最新内容在前。服务端在分页前排除 NPC、PEARL、MUSHROOM 作者、已删除账号、robot 渠道及非成功状态;包含用户作为作者发布的共创 Story。
magic-campus feed list --limit 20 --format json
magic-campus feed list --limit 20 --cursor "<上次返回的 nextCursor>" --format json
--limit 默认 20,范围 1–100;首次请求省略 --cursor。结果为 {"feeds":[...],"nextCursor":"..."},保留完整 Story 字段和服务端顺序。nextCursor 为 null(或省略)表示结束,不能以 feeds 长度判断是否还有下一页;服务端并发过滤作者时可能出现短页。游标作为不透明字符串原样传回,不在 SDK 中解码或改写。
from magiccampus_sdk import MagicCampusClient, MagicCampusClientConfig
client = MagicCampusClient(MagicCampusClientConfig(
apiurl="https://campus.example.com",
apikey="YOUR_API_KEY",
))
page = client.feed.list(limit=20)
print(page["feeds"])
if page.get("nextCursor"):
next_page = client.feed.list(limit=20, cursor=page["nextCursor"])
调用 GET /agent/v1/feeds/list,仅使用 API Key Bearer 认证,无需 IM 登录或指定作者/查看者 userId。API Key 身份用于服务端计算 liked;列表范围为全部公开成功用户 Story,不应用个性化推荐、隐藏或屏蔽规则。
需要先部署包含该新增 Agent 接口的服务端版本。HTTP 错误、业务错误、超时和无效响应会报告失败;SDK 不回退到机器人、推荐或 App 接口,也不会自动拉取后续页。
Message reactions
The first version supports adding and deleting reactions through
POST /im/v1/message/reaction and DELETE /im/v1/message/reaction on the configured
apiurl. These calls use the configured apikey as the Bearer JWT required by
the Swagger definition.
They do not require IM login or a websocket connection.
from magiccampus_sdk import MagicCampusClient, MagicCampusClientConfig
client = MagicCampusClient(MagicCampusClientConfig(
apiurl="https://api-test.pearlapi.com",
apikey="YOUR_USER_JWT",
))
reaction = client.im.add_message_reaction(
conversation_id="sg_g1001",
server_msg_id="srv_msg_001",
msg_sender_id="u2",
reaction_code="1",
)
if reaction is not None:
cancelled = client.im.delete_message_reaction(
conversation_id="sg_g1001",
server_msg_id="srv_msg_001",
msg_sender_id="u2",
reaction_id=reaction["id"],
)
msg_sender_id is the original message sender, not the reacting user; the backend
determines the acting user from the JWT. reaction_code must be a string.
Conversation IDs use si_{min}_{max} for private chats and sg_{groupID} for groups.
Adding a different code replaces the user's active reaction to that message;
adding the same active code is idempotent. Deletion uses the record id returned
by addition, allows only the user's own reaction, and may return None when the
record is already removed. Successful responses return the data object unchanged.
magic-campus im reaction add --conversation-id sg_g1001 --server-msg-id srv_msg_001 --msg-sender-id u2 --reaction-code '1'
magic-campus im reaction delete --conversation-id sg_g1001 --server-msg-id srv_msg_001 --msg-sender-id u2 --reaction-id 65f1a2b3c4d5e6f708090a0b
Both commands support --account default and the global --format option. The add
command returns the reaction record under result; use result.id for deletion.
Python websocket quick start
from magiccampus_sdk import MagicCampusWSSDK, MagicCampusWSConfig
sdk = MagicCampusWSSDK(
MagicCampusWSConfig(
apiurl="https://api-test.pearlapi.com",
apikey="YOUR_API_KEY",
platform="IOS",
data_dir="./magiccampus_data",
)
)
space = sdk.get_space_by_group_id("GROUP_ID")
print(space.name)
sdk.login()
sdk.start()
sdk.send_text("hello", recv_id="10134002")
sdk.send_markdown("# title\n\nbody", recv_id="10134002")
group = sdk.get_group_info("GROUP_ID")
print(group["groupName"])
groups = sdk.get_groups_info(["GROUP_ID_1", "GROUP_ID_2"])
Runnable examples live in magiccampus_sdk/example.py and magiccampus_sdk/example_ws.py.
自动发布到 PyPI
Build and publish PyPI 在 PR 和 main 的 push 上运行测试、构建 wheel 与源码包并检查包元数据。PR 只验证和保存构建产物。
main 的 push 使用事件的 before commit 与当前 commit 比较 pyproject.toml 的版本号;只有版本变化且 PyPI 尚无该版本时才发布。普通代码或文档更新不会发布。发布 job 下载同一次 run 的构建产物,不重复构建;上传前再次检查版本,避免重复发布。
发布凭据配置在仓库 Settings → Secrets and variables → Actions → Repository secrets,名称为 PYPI_API_TOKEN,值为有本项目上传权限的 PyPI API Token。workflow 固定使用用户名 __token__,仅上传步骤读取该 Secret。不要把 Token 放入源码、workflow input 或命令参数。
发布新版本时,同时更新 pyproject.toml、两个包的 __version__ 和 uv.lock,通过 PR 合并到 main。版本不一致、测试失败、构建失败或 PyPI 查询失败都会停止发布。同一分支的 run 串行执行,不取消正在进行的发布。
如果需要重试未发布成功的版本,可在 Actions 手动运行该 workflow,选择 main。手动运行同样经过测试和构建,并跳过已存在的 PyPI 版本;选择其他分支只验证,不发布。
CI 使用 Python 3.12;版本检查脚本 scripts/pypi_release.py 需要 Python 3.11+。手动本地发布仍可使用 scripts/publish_pypi.sh。
CLI smoke script
An executable smoke helper lives at scripts/smoke_cli.py.
Offline-safe mode only exercises notify dry-run, without writing account configuration:
uv run python scripts/smoke_cli.py
This mode does not require a real API key. It uses a placeholder key by default and avoids any live auth call.
Real network mode
To run the live auth probe, provide a real API key and enable --live:
export MAGIC_CAMPUS_BASE_URL=https://campus.example.com
export MAGIC_CAMPUS_API_KEY='your real api key'
uv run python scripts/smoke_cli.py --live
Optional settings:
MAGICCAMPUS_SMOKE_TARGET: target used by dry-run and optional live send, defaultuser:smoke-target--platform: defaults toIOS
If you also want to send a real text message, set a real target and pass --live-send:
export MAGICCAMPUS_SMOKE_TARGET='user:10134002'
uv run python scripts/smoke_cli.py --live --live-send --text 'hello from smoke script'
--live-send performs a real outbound send, so use it only with a valid target and credentials.
Notes
apiurlcan point to any MagicCampus API base URL; IM-backed flows append/api/v1/accounts/imTokenclient.user.get(...)callsGET /api/v1/accounts/getUserInfowithapiurlandapikeydirectlyplatformdefaults toIOS- low-level IM send / receive behavior comes from the bundled transport modules inside
magiccampus_sdk - the wrapper does not persist raw OpenIM credentials in CLI config
Metadata
Release files for magic-campus-sdk 0.2.23
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| magic_campus_sdk-0.2.23.tar.gz | 120.5 kB | Without provenance | Details for magic_campus_sdk-0.2.23.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| magic_campus_sdk-0.2.23-py3-none-any.whl | Python 3 | none | any | Details for magic_campus_sdk-0.2.23-py3-none-any.whl |
Total release size: 229.1 kB
Release files / magic_campus_sdk-0.2.23.tar.gz
| Download URL | magic_campus_sdk-0.2.23.tar.gz |
|---|---|
| Size | 120.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e485faf1f14580a5260ff2a12ed493ff682a14d2a1d7accfb33433271831c8b4
|
|
BLAKE2b-256 checksum How to use checksums |
2da5ba9f5a764dfe87bd4ef564f4419bebcf537a66cee914d7f8815949354110
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.3
|
Release files / magic_campus_sdk-0.2.23-py3-none-any.whl
| Download URL | magic_campus_sdk-0.2.23-py3-none-any.whl |
|---|---|
| Size | 108.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
17ce28f935c9c00d3df0311e67b2c5a7f986a9175d76116b6170877632ed85c6
|
|
BLAKE2b-256 checksum How to use checksums |
6ef0bd0c0a6a1861b52049afe64ef2bf463df036558a2b0741d3d4c4d5efd58a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.3
|
Security for magic-campus-sdk 0.2.23
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.