API 参考

MacroAI API 参考

图像识别

image_find(tmpl, region?, threshold?, match_mode?, transform_policy?) -> ImageMatchResult | nil
image_wait(tmpl, timeout?, region?, threshold?, interval?, match_mode?, transform_policy?) -> ImageMatchResult | nil
image_find_all(tmpl, region?, threshold?, match_mode?, transform_policy?) -> table | nil
image_wait_all(tmpl, timeout?, region?, threshold?, interval?, match_mode?, transform_policy?) -> table | nil

参数说明: - tmpl (string | table) — 模板图片,支持以下格式: - 单模板字符串(如 "button.png""button"),自动在 resources/images/ 下查找 - 相对路径 "resources/images/icon.png",相对项目目录解析 - 绝对路径 "D:/images/icon.png",直接使用 - 多模板 Lua 表 {"a.png", "b.png"},截屏一次遍历匹配,返回最佳结果 - 变量引用 var_get('btn_name')、参数引用或 u|var_id 用户配置引用 - region (table, 可选) — 搜索区域 {left, top, width, height},不传则搜索全屏或默认区域 - threshold (number, 可选) — 匹配阈值,范围 0~1,默认 0.85,越低越容易匹配 - timeout (number, 可选) — 超时秒数,默认 10(仅 image_wait / image_wait_all) - interval (number, 可选) — 轮询间隔秒数,默认 0.2(仅 image_wait / image_wait_all) - match_mode (string, 可选) — 匹配模式:"grayscale"(灰度,默认)、"luminance"(感知亮度)、"oklab"(OKLab 色彩) - transform_policy (string, 可选) — 坐标转换策略:"default"(跟随项目设置,默认) - img — 图像数据(numpy 数组)

返回值 (ImageMatchResult): - .success (boolean) — 是否找到 - .x, .y (number) — 匹配区域左上角坐标 - .center_x, .center_y (number) — 匹配区域中心坐标 - .width, .height (number) — 匹配区域尺寸 - .confidence (number) — 置信度 - .rect (table) — {left, top, width, height} - .template_name (string) — 匹配成功的模板文件名(仅含文件名,不含路径。多图查找时可判断哪个模板匹配上)

示例:

local r = image_find("login_btn.png", {100, 200, 800, 600}, 0.8)
if r and r.success then
    mouse_click(r.center_x, r.center_y)
end

返回全部匹配结果:

image_find_all(tmpl, region?, threshold?) -> table | nil
image_wait_all(tmpl, timeout?, region?, threshold?) -> table | nil
  • 返回所有匹配结果的数组,无匹配则返回 nil
  • 每个元素字段与 ImageMatchResult 相同
  • 适用于同一模板在屏幕上出现多次的场景
  • image_wait_all 轮询直到至少一个匹配出现,然后返回全部匹配

示例(查找并点击全部匹配):

local results = image_find_all("icon.png")
if results then
    for _, r in ipairs(results) do
        mouse_click(r.center_x, r.center_y)
        wait(500)  -- 点击间隔
    end
end

多模板查找(一次截屏遍历多个模板,返回最佳匹配):

local r = image_find({"btn_ok.png", "btn_cancel.png"})
if r and r.success then
    -- 通过 template_name 判断匹配的是哪个模板
    if r.template_name == "btn_ok.png" then
        log("确认按钮")
    end
end

多模板 + user_config_list 混合:

-- 在节点编辑器中多图列表填写: icon.png, u|uc_avatar
-- 生成代码自动构建混合列表
local _tmpls = {}
table.insert(_tmpls, 'icon.png')
for _, _v in ipairs(user_config_list('uc_avatar')) do
    table.insert(_tmpls, _v)
end
local r = image_find(_tmpls)
if r and r.success then
    log("匹配成功: " .. r.template_name)
end

OCR

ocr_recognize(region?, lang?) -> string
ocr_compare(text, region?, threshold?, lang?) -> OcrCompareResult
ocr_find_text(text, region?, lang?) -> number, number
ocr_log(msg) -> void

参数说明: - region (table, 可选) — 识别区域 {left, top, width, height},不传则全屏 - lang (string, 可选) — 语言代码,如 "zh-CN""en-US",不传则使用系统默认 - text (string) — 要匹配的文字 - threshold (number, 可选) — 相似度阈值,默认 0.8 - msg (string) — 日志消息

返回值 (OcrCompareResult): - .matched (boolean) — 是否匹配 - .found_text (string) — 识别到的文字 - .similarity (number) — 相似度 - .confidence (number) — 置信度

ocr_find_text 返回值: - 成功: center_x, center_y (number, number) - 失败: nil, nil

示例:

local text = ocr_recognize({100, 100, 500, 100}, "zh-CN")
ocr_log("识别到文字: " .. text)

local r = ocr_compare("确定", {100, 100, 500, 100})
if r and r.matched then
    log("匹配成功,相似度: " .. r.similarity)
end

local x, y = ocr_find_text("提交", {100, 100, 500, 100})
if x then mouse_click(x, y) end

鼠标

mouse_click(x?, y?, button?, clicks?) -> void
mouse_move(x?, y?) -> void
mouse_double_click(x?, y?) -> void
mouse_right_click(x?, y?) -> void
mouse_scroll(clicks, x?, y?) -> void
mouse_drag(sx, sy, ex, ey, button?, duration?) -> void

参数说明: - x, y (number, 可选) — 屏幕坐标,不传则在当前位置操作 - button (string, 可选) — 鼠标键,可选:"left"(默认)、"right""middle" - clicks (number) — 滚轮滚动格数,正数向上,负数向下 - sx, sy (number) — 拖拽起点 - ex, ey (number) — 拖拽终点 - duration (number, 可选) — 拖拽持续时间(秒),默认 0.3

示例:

mouse_click(500, 300)              -- 左键点击 (500,300)
mouse_click(500, 300, "right")     -- 右键点击
mouse_double_click(500, 300)       -- 双击
mouse_move(100, 200)               -- 移动到 (100,200)
mouse_drag(100, 100, 500, 300)     -- 从 (100,100) 拖拽到 (500,300)
mouse_scroll(3)                    -- 向下滚动 3 格

键盘

key_press(key) -> void
key_type(text) -> void
key_hotkey(key1, key2, ...) -> void
key_shortcut(combo) -> void
key_stroke(vk, scan, is_down?) -> void

参数说明: - key (string) — 按键名,如 "enter""tab""escape""a""ctrl" 等 - text (string) — 要输入的文本,换行符将自动转为 Enter - key1, key2, ... (string...) — 组合键序列,如 ("ctrl", "c") - combo (string) — 快捷键组合,如 "ctrl+c""alt+tab" - vk (number) — 虚拟键码(Virtual-Key Code) - scan (number) — 扫描码 - is_down (boolean, 可选) — true 按下,false 释放,不传则执行一次按下+释放

示例:

key_press("enter")                  -- 按回车
key_type("Hello, World!")           -- 输入文本
key_hotkey("ctrl", "c")            -- 按 Ctrl+C(序列按键)
key_shortcut("ctrl+c")             -- 按 Ctrl+C(组合键)
key_stroke(0x70, 0x3B)            -- 按下 F1 键(虚拟键码 0x70)

屏幕

screen_size() -> width, height

示例:

local w, h = screen_size()
log("屏幕分辨率: " .. w .. "x" .. h)

等待

wait(milliseconds) -> void
wait_seconds(seconds) -> void

示例:

wait(1000)        -- 等待 1000 毫秒(1 秒)
wait_seconds(2.5) -- 等待 2.5 秒

变量

var_set(name, value, scope?) -> void
var_get(name) -> any
var_has(name) -> boolean

参数说明: - name (string) — 变量名 - value (any) — 变量值(支持 string、number、boolean、table) - scope (string, 可选) — 作用域,可选:"local"(默认,仅当前脚本可见)、"global"(跨脚本共享)

示例:

var_set("count", 10)
var_set("name", "MacroAI", "global")

local c = var_get("count")
log("count = " .. c)

if var_has("name") then
    log("name 变量存在")
end

区域

region_get(name) -> Region | nil
getRegion(name?) -> {left, top, width, height} | nil
to_runtime_region(region) -> {left, top, width, height}
to_runtime_point(x, y) -> number, number

参数说明: - name (string) — 区域名称 - left, top, width, height (number) — 区域矩形(设计区域坐标) - region (table) — {left, top, width, height} 格式的区域

说明: - region_get 返回 Region 对象(带 .left, .top, .width, .height 属性) - getRegion 返回 Lua table,可指定名称,不传或传 "__effective__" 返回默认搜索区域 - to_runtime_region / to_runtime_point 将设计区域坐标转换为运行时坐标(多分辨率适配)

示例:

local r = region_get("dialog")
if r then
    log("区域: " .. r.left .. "," .. r.top)
end

local rt = getRegion("dialog")           -- {left, top, width, height}
local eff = getRegion()                  -- 默认搜索区域
local pt_x, pt_y = to_runtime_point(500, 300)  -- 转换为运行区域坐标

变化检测

detect_change(kwargs?) -> table
wait_change(kwargs?) -> table
wait_bar_change(kwargs?) -> table

kwargs 参数表:

detect_change / wait_change 通用参数

参数 类型 默认值 说明
region table 全屏 检测区域 {left, top, width, height}
block_size number 50 网格大小(像素)
threshold number 30.0 变化阈值(灰度差值)
min_area number 900 最小变化面积
timeout number 30 超时秒数(仅 wait_change)
interval number 1.0 轮询间隔秒数(仅 wait_change)
track_frames number 10 跟踪帧数(仅 wait_change,用于过滤周期性变化)
cyclic_ratio number 0.7 周期性过滤比例(仅 wait_change)

wait_bar_change 参数

参数 类型 默认值 说明
region table 全屏 检测区域
timeout number 30 超时秒数
interval number 0.5 轮询间隔秒数
min_change number 0.1 最小变化比例
match_threshold number 0.85 模版匹配相似度阈值
orientation string "auto" 条块方向:"horizontal""vertical""auto"
reset boolean false 是否重置历史追踪(场景切换时使用)
templates table[] 必填 模板配置数组(见下方)

templates 配置格式:

{
    {
        label = "hp_full",             -- 模版名称,同时也是文件名
        template_path = "resources/bar_templates/hp_full.png",
        color_swatch = {255, 50, 50}   -- 由系统自动生成,可不填
    },
    {
        label = "hp_half",
        template_path = "resources/bar_templates/hp_half.png",
        color_swatch = {50, 50, 255}
    }
}

返回值: - detect_change / wait_change 返回变化区域数组: lua { { center_x = 350, center_y = 250, rect = {340, 240, 20, 20} }, ... } - wait_bar_change 返回条块变化数组: lua { { rect = {100, 200, 300, 20}, -- 条块边界框 center_x = 250, -- 条块中心 X center_y = 210, -- 条块中心 Y label = "hp_full", -- 匹配上的模版标签 state = "changed", -- changed/resized/disappeared/appeared delta = 0.5, -- 宽度比例变化(新 label 宽度 / 旧 label 宽度) reference_value = 1.0, -- 旧 label 宽度比例 curr_value = 0.5, -- 新 label 宽度比例 orientation = "horizontal" }, ... }

示例:

-- 检测条块变化(上传两个宽度不同的模版,引擎自动匹配)
local bar_changes = wait_bar_change({
    region = {100, 50, 300, 20},
    timeout = 15,
    templates = {
        {
            label = "full",
            template_path = "resources/bar_templates/full.png",
        },
        {
            label = "half",
            template_path = "resources/bar_templates/half.png",
        }
    }
})

-- 只处理真实变化,忽略移入移出
for _, bc in ipairs(bar_changes) do
    if bc.state == "changed" or bc.state == "resized" then
        log("条块变化: " .. bc.label .. " delta=" .. bc.delta)
    end
end
reset_bar_detector() -> void

重置所有条块追踪缓存。进入新界面时调用,避免旧追踪状态干扰新场景。

参数 类型 说明
- -

示例:

-- 进入新场景时重置追踪
reset_bar_detector()

local bars = wait_bar_change({
    region = {100, 50, 300, 20},
    templates = {
        { label="full", template_path="resources/bar_templates/full.png" },
        { label="half", template_path="resources/bar_templates/half.png" },
    }
})

颜色检测

color_get_pixel(x, y) -> table
color_get_dominant(region?, kwargs?) -> table
color_find(kwargs?) -> table
color_is(detected, target, threshold?) -> boolean
color_distance(c1, c2) -> number

参数说明: - x, y (number) — 屏幕坐标 - region (table, 可选) — 检测区域 {left, top, width, height},不传则全屏 - kwargs (table, 可选) — 参数字典: - region — 搜索区域 - color — 目标颜色 {r, g, b}(color_find 使用) - detected (table) — 检测到的颜色值 {r, g, b} - target (table) — 目标颜色值 {r, g, b} - threshold (number, 可选) — 颜色距离阈值,默认 30 - c1, c2 (table) — 两个颜色值 {r, g, b}

color_get_pixel 返回值: - {r, g, b} 形式,各分量范围 0~255

color_get_dominant 返回值: - {r, g, b} 形式的主色调

color_find 返回值: - 找到返回 {x, y},未找到返回 nil

color_is 返回值: - true / false

color_distance 返回值: - 颜色距离值(数值,越小越接近)

示例:

local pixel = color_get_pixel(500, 300)
log("像素颜色: " .. pixel.r .. "," .. pixel.g .. "," .. pixel.b)

local dominant = color_get_dominant({100, 100, 200, 200})
log("主色调: " .. dominant.r .. "," .. dominant.g .. "," .. dominant.b)

local found = color_find({region={0, 0, 1920, 1080}, color={255, 0, 0}})
if found then
    log("找到红色位置: " .. found.x .. "," .. found.y)
end

if color_is({255, 50, 50}, {255, 0, 0}, 60) then
    log("颜色近似匹配")
end

local dist = color_distance({255, 0, 0}, {200, 0, 0})
log("颜色距离: " .. dist)

音频

play_warning(sound_type, custom_file?) -> void
play_music(filepath) -> void
is_music_playing() -> boolean

参数说明: - sound_type (string) — 音效类型: - 系统音效:"ding""error""warning""question""info" - 系统声音:"startup""shutdown""chimes""tada" - 音符:"do""re""mi""fa""sol""la""si"(蜂鸣器) - 自定义:"custom" - custom_file (string, 可选) — 自定义 WAV 文件路径(sound_type 为 "custom" 时使用) - filepath (string) — 音乐文件路径(支持 MP3、WAV 等格式)

示例:

play_warning("ding")              -- 播放提示音
play_warning("custom", "C:\\alert.wav")  -- 播放自定义 WAV

play_music("C:\\bgm.mp3")        -- 播放背景音乐
if is_music_playing() then
    log("音乐正在播放")
end

日志

log(message) -> void
ocr_log(msg) -> void
trace_log(msg) -> void
print(...) -> void

示例:

log("脚本开始执行")
ocr_log("OCR 识别结果: " .. text)
print("变量值:", x, y, z)  -- 输出: 变量值: 100 200 300

通知

show_dialog(text, image?, btn_text?) -> void
show_toast(text, image?, duration?) -> void

参数说明: - text (string) — 通知文本内容 - image (string, 可选) — 显示的图片路径 - btn_text (string, 可选) — 对话框按钮文字(默认 "确定") - duration (number, 可选) — Toast 显示时长(秒),默认 3

说明: - show_dialog 弹出模态对话框,需用户确认后继续 - show_toast 显示系统 Toast 通知,自动消失

示例:

show_dialog("操作完成!")
show_toast("任务执行成功", 5)
show_dialog("请确认操作", "C:\\image.png", "好的")

用户配置变量

user_config(var_id) -> string
user_config_list(var_id) -> table

参数说明: - var_id (string) — 用户配置变量的 ID(定义时自动添加 uc_ 前缀,引用时以 u| 开头)

说明: - user_config 返回用户配置变量的值(文本字符串或图片的绝对路径) - user_config_list 返回图像类型用户配置的文件绝对路径列表(用于多图展开) - 图片存储在 resources/user_config/ 目录,引擎自动解析 name_id 为绝对路径 - 单图类型配合 image_findu|var_id 引用在生成代码层展开

示例:

local nickname = user_config("uc_nickname")
log("用户昵称: " .. nickname)

local images = user_config_list("uc_avatar")
for _, path in ipairs(images) do
    log("图片绝对路径: " .. path)
end

-- 在 image_find 中直接使用(生成代码自动处理)
-- image_find({"fixed.png", user_config("uc_avatar")})

检查停止

check_stop() -> void

在执行循环或长时间操作时调用,使脚本能够响应暂停和停止信号。如果用户在运行中点击了暂停或停止,check_stop() 会立即中断当前操作。

引擎在部分长时间操作中会自动注入此调用,但自定义循环中建议主动调用。

示例:

for i = 1, 100 do
    check_stop()  -- 让用户可以随时中止
    -- 执行操作...
    wait(500)
end

通用约定

坐标系统

  • 所有坐标单位为像素
  • 区域格式统一为 {left, top, width, height}
  • 坐标会自动根据设计区域和运行区域缩放适配(多分辨率)

返回值约定

  • 成功返回有效值,失败返回 nil
  • ImageMatchResult 可通过 if r and r.success 判断是否匹配成功