Skip to content

图片渲染 ​

maworld 通过模板数据、渲染器与浏览器后端生成图片。一般业务插件优先使用事件运行时,不直接创建浏览器实例。

目录约定 ​

text
plugins/my-plugin/
├─ index.js
└─ resources/
   └─ card/
      ├─ index.html
      └─ style.css

调用 e.runtime.render('my-plugin', 'card/index', data),模板对应 plugins/my-plugin/resources/card/index.html。插件目录名必须与第一个参数一致。

模板示例 ​

html
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <style>
    body { margin: 0; width: 640px; font-family: sans-serif; background: #101827; color: #eef6ff; }
    .container { box-sizing: border-box; width: 640px; padding: 40px; }
    h1 { color: #5eead4; }
    footer { margin-top: 32px; color: #c1ccdc; }
  </style>
</head>
<body>
  <main class="container">
    <h1>{{title}}</h1>
    <p>{{message}}</p>
    <footer>{{@copyright}}</footer>
  </main>
</body>
</html>

模板使用 art-template。普通插值会转义 HTML;只有受信任的框架署名等内容使用原始 HTML 输出。不要把用户输入直接送入未转义插值。

自动回复 ​

js
async function renderAndSend(e) {
  return e.runtime.render('my-plugin', 'card/index', {
    title: '系统卡片',
    message: '这是一张 maworld 图片',
  })
}

默认调用会自行回复图片。此时不要再把返回值当作图片传给 e.reply()。

返回图片后自行发送 ​

js
async function renderAsMessage(e) {
  const image = await e.runtime.render('my-plugin', 'card/index', {
    title: '你好',
    message: e.msg || '',
  }, { retType: 'base64' })
  if (!image) return e.reply('渲染失败,请查看控制台')
  return e.reply(image)
}

retType: 'base64' 是沿用的选项名。当前链路返回可发送的图片内容,通常是图片消息段;不要假定可以直接作为裸 Base64 字符串拼接。

常用数据与选项 ​

名称用途
data.saveId / data.save_id临时 HTML 保存标识
data.tplFile运行时按插件与模板目录构造
data.pluResPath / _res_path插件资源相对路径
data.framework真实框架信息
data.copyright标准署名 HTML
options.beforeRender截图前调整数据,返回新数据或沿用原数据
options.retType: 'base64'返回图片内容而不自动回复
options.retType: 'msgId'自动发送后返回回复接口的结果,不保证是纯消息 ID
js
async function renderWithData(e) {
  return e.runtime.render('my-plugin', 'card/index', { title: '卡片' }, {
    beforeRender({ data }) {
      return { ...data, message: `版本 ${data.framework.version}` }
    },
  })
}

this.renderImg(pluginName, tpl, data, options) 还会经过兼容图片辅助入口;需要复用该入口的旧插件应核对其返回与发送行为。新代码可直接使用运行时,减少隐式步骤。

署名和数据隔离 ​

标准渲染会在数据副本中处理框架署名,保留插件作者、名称和版本。自定义正文、其他变量和远程图片不会被统一替换。

渲染器对相同临时 HTML 路径的操作提供串行保护;并发卡片仍建议使用合适的 saveId,减少不同业务之间的文件名冲突。不要用用户输入直接构造任意模板路径。

调试 ​

sh
pnpm dev

开发模式会把运行时渲染数据保存到 temp/ViewData/插件名/。实际临时模板位于 temp/html/。检查模板是否能读到、数据是否正确、网络图片是否可达,再排查浏览器或协议发送。

浏览器路径、远程 WebSocket 和截图超时见配置说明。

TypeScript + Node.js · 文档对应 maworld 1.0.0