vtapi:静默只读查询库
vtapi 是一个纯 Python 插件库:不用改 C++、不用重新编译客户端,只使用官方已有的 原生 API 拼出一条静默查询通道,用来读取游戏内状态:
| 能力 | 入口 | 典型耗时 |
|---|---|---|
| 背包物品数量 | vtapi.bag.count() / has() | 约 0.6 秒(7 次往返) |
| 计分板分数 | vtapi.score.get() | 约 0.1 秒(1 次往返) |
| 玩家坐标 | vtapi.pos.get() / scan() / block() | 缓存命中 0 秒;扫描约 1.2 秒 |
查询全程不产生命令回执(不依赖 sendCommandFeedback)、不会出现在任何玩家的聊天框, 也不修改游戏内任何状态。它是只读的。
为什么需要它
原生接口 engine.command_guid() 的回执受 gamerule sendCommandFeedback 门控: 打开会刷屏(管理员能看到全部回执,普通玩家也可能看到广播),关掉则完全收不到回执。 engine.settingscommand() 虽然静默,但永远不产生 CommandOutput。 详见命令回执机制。
vtapi 换了一条完全不经过命令回执的通道:让服务端在展开 tellraw 的 selector / score 组件时,把答案当作聊天文本回给机器人自己。
通道原理
# 机器人用 setting 指令给自己发一条 tellraw(静默、无回执)
/tellraw "机器人名" {"rawtext":[{"text":"VTPROBE<随机串>|"},{"selector":"@a[name=...]"}]}- 机器人通过
engine.settingscommand()发出这条tellraw - 服务端把
selector/score组件在服务端展开成文本,回一个TextPacket(0x09) - 插件在
on_text事件里按随机串(nonce)匹配回包 - 命中 → 回包里出现展开文本;未命中 → 组件被丢弃,但消息仍然到达 → 判为“有效否定”
- 完全没有回包 → 判为
unknown,按tries自动重试
为什么不会刷屏
tellraw 的目标是机器人自己,消息只发给机器人这一个客户端;整条链路不经过 CommandOutput,因此既与 sendCommandFeedback 无关,也不会出现在其他玩家的聊天里。
一条 tellraw 可以合并多个查询
内部函数 _query_multi() 会在一条 tellraw 里塞入多个带标记的查询组件(实测 3 个稳定), pos.scan() 正是用它把 X / Y / Z 三轴探针合并成一条消息,把扫描往返压到约 10 次。
安装
把 vtapi 包整个复制到插件目录即可,作为普通插件被加载:
scripts/
└─ vtapi/
└─ vtapi/
└─ __init__.py # 只需要这一个文件在自己的插件里直接 import vtapi(init.py 已把 scripts/<插件名> 加入 sys.path, vtapi 会被当作同级插件模块导入)。也可以把它放到任意已在 sys.path 中的目录。
运行前提:
| 条件 | 说明 |
|---|---|
| 机器人在线 | game_state.has_local_player() 为 True |
| 机器人有 op 权限 | tellraw 给任意目标、读取任意玩家数据都需要管理员(权限等级 ≥ 2) |
| 在后台线程调用 | 见下方 danger 提示 |
| 网易协议客户端 | 本库按网易版 settingscommand 行为编写(协议 898 / MCBE 1.21.130) |
必须在后台线程调用
不要在 on_text、on_init 之类的事件回调里同步调用 vtapi。这些回调运行在客户端 事件线程上,而 vtapi 需要等待同一个线程分发的回包 —— 会把自己锁死,直到 timeout 超时。正确做法是 threading.Thread(target=...) 起线程,并在 on_uninit() 里停止线程(热重载要求)。
快速开始
import threading
import time
import vtapi
_stop = threading.Event()
_thread = None
def _loop():
while not _stop.is_set():
r = vtapi.pos.get('Steve')
if r['status'] != 'ok':
r = vtapi.pos.scan('Steve', radius=16)
if r['status'] == 'ok':
print('Steve at %.2f %.2f %.2f' % (r['x'], r['y'], r['z']))
time.sleep(1.0)
def on_init(args):
global _thread
_thread = threading.Thread(target=_loop, daemon=True)
_thread.start()
def on_uninit(args):
_stop.set()
if _thread is not None:
_thread.join(timeout=2.0)
engine.register(on_init, 'ModEventStartUp')
engine.register(on_uninit, 'ModEventUnInit')先做一次自检
插件加载后先调用 vtapi.self_test() 确认通道可用(机器人是否有 op、回包是否还能收到):
st = vtapi.self_test()
# {'version': '1.1.0', 'has_player': True, 'bot_name': 'bot', 'text_hook': True,
# 'command_ok': True, 'probe_status': 'ok', 'detail': None}
if not st['command_ok']:
print('vtapi channel down:', st['probe_status'], st['detail'])API 参考
模块级函数
| 函数 | 说明 |
|---|---|
vtapi.init() | 预注册 on_text 钩子与 MovePlayer 监听,返回 {'text_hook', 'move_hook', 'has_player'};模块被加载时会自动调用一次 |
vtapi.on_uninit() | 注销 on_text 钩子(热重载 / 卸载时调用) |
vtapi.self_test(timeout=3.0, tries=2) | 一次自检,返回 version / has_player / bot_name / text_hook / command_ok / probe_status / detail |
vtapi.status() | 运行时统计:version / has_player / bot_name / text_hook / move_hook / waiters / queries / timeouts / unknowns / cached_entities / bound_players |
vtapi.VERSION | 版本字符串,当前 '1.1.0' |
vtapi.bag —— 背包物品数量
全部走 hasitem 选区(跨堆叠合计,不区分槽位)。
| 函数 | 返回 |
|---|---|
bag.has(player, item, count=1, timeout=3.0, tries=3) | {'status': 'ok', 'has': bool, 'count_at_least': count} |
bag.count(player, item, timeout=3.0, tries=3, max_check=4096) | {'status': 'ok', 'count': n, 'verified': bool, 'lower_bound': False, 'queries': n} |
bag.count_many(player, items, timeout=3.0, tries=3) | {item: 上面 count() 的结果} |
count() 用 quantity=N.. 阈值二分:先 1.. 判断有没有,再以 2 的幂上探,最后二分; 末次 quantity=n 精确核对不通过时 verified=False(罕见抖动,count 仍可信)。 数量 ≥ max_check 时直接返回 lower_bound=True,不再向上翻。
import vtapi
vtapi.bag.has('Steve', 'minecraft:diamond', 64) # -> {'status': 'ok', 'has': True, ...}
vtapi.bag.count('Steve', 'minecraft:stone') # -> {'status': 'ok', 'count': 128, 'verified': True, ...}
vtapi.bag.count_many('Steve', ['minecraft:bread', 'minecraft:arrow'])物品名格式
与游戏内指令一致,建议带命名空间(minecraft:diamond),自定义物品直接写完整 id。 名字只允许 [A-Za-z0-9_:.-],非法字符会抛 ValueError。
vtapi.score —— 计分板分数
用 tellraw 的 score 组件展开,不产生命令回执。
| 函数 | 返回 |
|---|---|
score.get(player, objective, timeout=3.0, tries=3) | {'status': 'ok', 'value': int 或 str, 'raw': str, 'objective': str} |
或 {'status': 'no_score', 'objective': str}(该玩家此计分项不存在) | |
score.get_many(player, objectives, timeout=3.0, tries=3) | {objective: 上面的结果} |
r = vtapi.score.get('Steve', 'money')
if r['status'] == 'ok':
print('money =', r['value']) # 数值会被转成 int,非数字时保留原始字符串
elif r['status'] == 'no_score':
print('玩家没有 money 计分项')objective 只允许 [A-Za-z0-9_]{1,32}(计分项名本身不允许中文与空格)。
vtapi.pos —— 坐标
被动通道来自 MovePlayer(0x13) 结构化协议事件,主动通道是服务端选区三轴二分。 机器人自己不会移动,也不产生命令回执、不进聊天。
| 函数 | 说明 |
|---|---|
pos.install() | 注册 MovePlayer(0x13) 结构化回调,返回 bool(已注册时直接返回 True) |
pos.watch(player=None, seconds=5.0, timeout=3.0, tries=2) | 监听 seconds 秒内的移动包;给了 player 会顺带绑定 runtime_id。返回 {'status': 'ok', 'packets': n, 'bound': {...} 或 None, 'cached_entities': n} |
pos.get(player, fresh=5.0, timeout=3.0, tries=2) | 读缓存坐标。fresh 秒内有效,过期会尝试重新绑定;仍过期返回 stale |
pos.scan(player, center=None, radius=48, timeout=3.0, tries=3, precision=0.05) | 主动选区二分定位(见下) |
pos.get_or_scan(player, center=None, radius=48, fresh=5.0, timeout=3.0, tries=2, precision=0.05) | 缓存优先,失败时退回 scan() |
pos.block(player, radius=64) | 返回整数三元组 (x, y, z) 或 None |
pos.get() 成功(ok / stale)时字段:
| 字段 | 说明 |
|---|---|
x / y / z | 客户端 position,即眼睛高度(脚底 = y - 1.62) |
block | {'x', 'y', 'z'} 向下取整的方块坐标 |
age | 距该条 MovePlayer 包的秒数 |
runtime_id | 绑定到的实体 runtime id |
source | 固定为 'move' |
pos.scan() 成功时字段:x / y / z / feet_y / block / precision / queries / source='scan'。
import vtapi
vtapi.pos.install() # 只需一次
r = vtapi.pos.get('Steve')
if r['status'] != 'ok':
r = vtapi.pos.scan('Steve', radius=16, precision=0.05)
print(r.get('block')) # {'x': 100, 'y': 64, 'z': -20}返回结构约定
所有查询函数都返回 dict,用 status 区分结果,不抛异常(参数非法除外):
| status | 含义 | 建议处理 |
|---|---|---|
ok | 查询成功,字段齐全 | 直接使用 |
no_match / no_score | 服务端明确回答“没有”(组件被丢弃) | 视为有效否定,不要重试 |
out_of_range | scan():目标不在搜索盒内 | 换 center 或加大 radius |
stale | 缓存超过 fresh,但仍在 60 秒内 | 可继续用,或调 scan() 刷新 |
no_data | 没有数据(无 MovePlayer 包、机器人坐标未知等) | 改用 scan() / 传 center |
not_ready | 机器人不在游戏内,或名字未知 | 等待登录完成 / 检查 has_player |
unknown | 重试后仍没有回包 | 查 self_test(),可能是 op 缺失或僵尸连接 |
None 只出现在 pos.block()(返回三元组或 None)。
定位几何
网易版选区体积盒按 [x, x+dx+1) 与实体碰撞箱相交判定命中(dx=0 即 1 格宽)。 玩家碰撞箱相对客户端 get_local_player()['position'] 为:
| 轴 | 相对 position 的范围 |
|---|---|
| X / Z | pos ± 0.3 |
| Y | [pos - 1.62, pos + 0.18] |
因此“交叉轴给超大跨度、单轴把盒起点当变量”时,命中条件在单轴上单调,可以二分到任意精度:
| 常量 | 值 | 含义 |
|---|---|---|
AABB_HALF | 0.3 | 碰撞箱半宽 |
AABB_EYE | 1.62 | 眼睛高度(position.y - 脚底) |
AABB_TOP | 0.18 | 头顶相对 position.y 的高度 |
PID_MOVE_PLAYER | 19 | MovePlayer 结构化协议事件 ID |
SEND_INTERVAL | 0.12 | 两次发送之间的强制最小间隔(秒) |
scan() 先发 1 条存在性检查盒,再按 precision 计算迭代次数 (ceil(log2(2 * radius / precision))),三轴并行二分;默认 radius=48、precision=0.05, 典型约 1 秒 / 10 次往返。房间 24350 实测标定误差:X / Z 约 0.003 格,Y 约 0.008 格。
选区半径不要开太大
radius 是立方搜索半径,体积盒体积按三次方增长,服务端对超大选区有额外开销; 不确定位置时优先用 get() 的被动缓存,其次 scan(radius=16~32)。
性能
2026-11-08 在房间 24350(MCBE 1.21.130 网易版)实测,单次往返约 80~110 ms, 发送间隔受 SEND_INTERVAL = 0.12 秒限速:
| 操作 | 往返次数 | 耗时 |
|---|---|---|
score.get() | 1 | 约 0.1 秒 |
bag.count()(7 个物品内) | 约 7 | 约 0.6 秒 |
pos.scan(radius=48) | 约 10 | 约 1.2 秒 |
pos.get()(缓存命中) | 0 | 立即返回 |
高频查询会掉回包
实测短时间连发 tellraw 超过约 60 条 / 10 秒会被服务端限流、开始丢回包。 vtapi 已在每次发送前强制 SEND_INTERVAL 间隔;如果你的循环仍然频繁,请自行加大 间隔或降低查询频率。
示例
示例 A:统计在线玩家背包
import threading
import vtapi
def report(players):
for name in players:
r = vtapi.bag.count(name, 'minecraft:diamond')
if r['status'] == 'ok':
print('%s 有 %d 颗钻石' % (name, r['count']))
else:
print('%s 查询失败: %s' % (name, r['status']))
threading.Thread(target=report, args=(['Steve', 'Alex'],), daemon=True).start()示例 B:分数达到阈值的判断
r = vtapi.score.get('Steve', 'level')
ok = r['status'] == 'ok' and isinstance(r['value'], int) and r['value'] >= 10示例 C:判断两个玩家距离
import math
import vtapi
a, b = vtapi.pos.get('Steve'), vtapi.pos.get('Alex')
if a['status'] == 'ok' and b['status'] == 'ok':
d = math.dist((a['x'], a['y'], a['z']), (b['x'], b['y'], b['z']))
print('距离 %.2f 格' % d)示例 D:线程 + 热重载模板
import threading
import vtapi
_stop = threading.Event()
_thread = None
def _worker():
while not _stop.is_set():
st = vtapi.status()
if not st['has_player']:
_stop.wait(1.0)
continue
r = vtapi.bag.count('Steve', 'minecraft:bread')
if r['status'] == 'ok':
print('bread =', r['count'])
_stop.wait(5.0)
def on_init(args):
global _thread
vtapi.init()
_stop.clear()
_thread = threading.Thread(target=_worker, daemon=True)
_thread.start()
def on_uninit(args):
_stop.set()
if _thread is not None:
_thread.join(timeout=2.0)限制与注意事项
只读
vtapi 只读取状态,不修改背包、分数、位置或任何游戏数据。需要写操作请用 engine.command() / engine.settingscommand()。
僵尸连接
高频查询若干十秒后,服务端会话可能整体失效:game_state.has_local_player() 仍为 True,但所有查询零回包(房间成员列表里机器人已消失)。此时只能重连机器人,用 vtapi.self_test() 可提前发现(command_ok=False)。
pos.get()依赖MovePlayer包:玩家长时间静止时缓存会stale,此时用scan()。pos.watch()的绑定靠“哪个移动实体落在该玩家的碰撞箱窗口里”,多个实体紧贴时可能绑错, 调用pos.get()前建议先pos.scan()校准一次。bag只统计hasitem能覆盖的物品,槽位信息请用game_state.get_inventory()。score的计分项必须已存在;不存在的项返回no_score而不是0。
排错
| 现象 | 原因 | 处理 |
|---|---|---|
全部返回 unknown | 无 op 权限、机器人未真正进服、僵尸连接 | 跑 self_test();确认权限等级 ≥ 2;重连 |
调用后卡住到 timeout | 在事件回调所在线程同步调用 | 移到后台线程(见上方 danger 提示) |
has() 永远 False | 物品名写错 / 玩家名写错 | 用带命名空间 id;玩家名区分大小写 |
scan() 返回 out_of_range | center / radius 没覆盖到目标 | 调大 radius 或传目标附近 center |
分数返回 no_score | 该玩家没有这个计分项 | 先用指令建项并赋分 |
| 热重载后不再回包 | 旧 on_text 钩子残留 / 旧线程还在跑 | 实现 on_uninit() 并调用 vtapi.on_uninit() |
下一步
- 命令回执机制:为什么
command_guid拿不到回执,以及其它回执渠道 - engine API:
settingscommand、command_guid、结构化协议事件 - 原生模块速查:
game_state、packets的原始接口
