app.shortcuts - Apple 快捷指令 API
运行和列出 Apple Shortcuts(快捷指令)。
需要 macOS 12.0+(Monterey),较早版本返回错误。
方法
app.shortcuts.run(name, opts?)
运行指定名称的快捷指令。
参数:
name(string) - 快捷指令名称opts(table, 可选):input(string|array) - 传递给快捷指令的输入内容
返回值: string, error - 快捷指令的输出文本
-- 运行快捷指令
local output, err = app.shortcuts.run("My Shortcut")
if not output then
app.log.error("运行失败: " .. err)
end
-- 传递文本输入
local result = app.shortcuts.run("Process Text", {
input = "Hello World"
})
-- 传递多行输入
local result = app.shortcuts.run("Process Files", {
input = {"/path/to/file1.txt", "/path/to/file2.txt"}
})
app.shortcuts.list()
列出用户所有的快捷指令。
返回值: array<table>, error - 每项包含:
name(string) - 快捷指令名称folder(string, 可选) - 所在文件夹
local shortcuts, err = app.shortcuts.list()
if shortcuts then
for _, s in ipairs(shortcuts) do
app.log.info("快捷指令: " .. s.name)
end
end
说明
- macOS 12.0+ 可用
- 输入通过标准输入传递给快捷指令
- 输出为快捷指令的标准输出文本
- 运行时间取决于快捷指令的复杂度,可能较长
示例
用快捷指令处理选中的文件
function MyPlugin:handleWithShortcut(context)
-- 列出可用的快捷指令让用户选择
local shortcuts = app.shortcuts.list()
if not shortcuts or #shortcuts == 0 then
app.dialog.alert("提示", "没有找到快捷指令")
return
end
local names = {}
for _, s in ipairs(shortcuts) do
table.insert(names, s.name)
end
-- 这里可以用对话框让用户选择...
-- 然后执行
local output, err = app.shortcuts.run(names[1], {
input = context.selectedFiles
})
if output then
app.notification.show("完成", output)
else
app.dialog.alert("错误", err or "快捷指令执行失败")
end
end
批量转换图片格式
function MyPlugin:handleConvertImages(context)
for _, file in ipairs(context.selectedFiles) do
local ext = app.path.extension(file)
if ext == "png" or ext == "jpg" then
local result, err = app.shortcuts.run("Convert to WebP", {
input = file
})
if result then
app.log.info("已转换: " .. file)
end
end
end
app.notification.show("完成", "处理了 " .. #context.selectedFiles .. " 个文件")
end