进阶教程 - 实用功能开发
在完成基础入门教程后,你已经学会了如何创建一个简单的插件。本教程将介绍更多高级功能,帮助你开发更强大的插件。
1. 使用 Network API 调用外部接口
network API 是 EasyBot 提供的 HTTP 客户端,支持 GET、POST、PUT、DELETE 等常见请求方法。
基础请求
/// <reference path="easybot-sdk/easybot.d.ts" />
// 发送 GET 请求
async function fetchData() {
const response = await network.get("https://api.example.com/data");
if (response.status === 200) {
logger.info("获取数据成功");
return response.data; // 自动 JSON 解析
}
logger.error(`请求失败,状态码: ${response.status}`);
return null;
}
发送 POST 请求
async function submitData(data) {
const response = await network.post(
"https://api.example.com/submit",
JSON.stringify(data)
);
return response.status === 200;
}
自定义请求头
async function apiCallWithAuth() {
const response = await network.request({
url: "https://api.example.com/protected",
method: "GET",
headers: {
"Authorization": "Bearer your-api-token",
"Content-Type": "application/json"
}
});
return response.data;
}
2. 使用 WebKit API 创建自定义页面
WebKit API 允许插件在 EasyBot 的 Web 管理界面中注册自定义页面和菜单。
注册一个简单页面
bus.on("menu_ready", (pluginMenu) => {
pluginMenu.register(
"hello_world", // ID
"/pages/hello", // 页面路径
"你好世界", // 菜单标题
"HomeOutlined", // 图标
(action) => { // 处理前端交互
if (action.method === "greet") {
return { message: `你好,${action.parameters.name}!` };
}
},
(sessionId) => { // 返回页面HTML
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>你好世界</title>
<style>
body { font-family: sans-serif; padding: 40px; text-align: center; }
input { padding: 8px; font-size: 16px; width: 200px; }
button { padding: 8px 16px; font-size: 16px; margin-left: 8px; }
#result { margin-top: 20px; font-size: 18px; color: #333; }
</style>
</head>
<body>
<h1>👋 你好世界</h1>
<p>输入你的名字:</p>
<input id="nameInput" type="text" placeholder="你的名字" />
<button onclick="sayHello()">打招呼</button>
<div id="result"></div>
<script>
async function sayHello() {
const name = document.getElementById('nameInput').value;
// 调用后端方法
const result = await window.webuikit.action('greet', { name });
document.getElementById('result').textContent = result.message;
}
</script>
</body>
</html>`;
},
null, // 父菜单(根级)
true, // 默认可见
10, // 排序
false // 不锁定
);
});