KV 存储与 HTTP
KV 命名空间
按「账号 + 机器人 + 插件」隔离:
text
u:{owner_id}:{botSlug}:{submissionId}只支持字符串。
基本操作
js
ctx.kv.set('count', String(1));
const raw = ctx.kv.get('count');
const count = Number(raw || '0');
ctx.kv.has('count'); // boolean
ctx.kv.keys(); // string[]
ctx.kv.delete('count');计数器示例
js
const key = `user:${ctx.userId}`;
const count = Number(ctx.kv.get(key) || '0') + 1;
ctx.kv.set(key, String(count));
await ctx.reply(`这是你第 ${count} 次使用`);配置示例
js
const prefix = ctx.kv.get('prefix') || '查询';不要依赖模块变量
模块顶层变量只在同一个 Worker 存活期间保留,服务重启会丢。
HTTP
js
const res = await ctx.http(url, {
method: 'GET',
headers: {},
body: '',
maxBytes: 1024 * 1024,
});返回:
js
{ status: 200, text: '...' }限制
| 项目 | 值 |
|---|---|
| 默认响应上限 | 5MB |
| 最大响应上限 | 20MB |
| 超时 | 15 秒 |
| 重定向 | 不跟随 |
| 内网地址 | 拒绝 |
GET JSON
js
const res = await ctx.http(`https://api.example.com/search?q=${encodeURIComponent(ctx.content)}`);
if (res.status !== 200) {
await ctx.reply(`接口异常:${res.status}`);
return true;
}
const data = JSON.parse(res.text);
await ctx.reply(String(data.answer ?? '没有结果'));POST JSON
js
const res = await ctx.http('https://api.example.com/v1/chat', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ message: ctx.content, user: ctx.userId }),
});错误处理
js
try {
// ...
} catch (e) {
ctx.error('请求失败', e && e.message);
await ctx.reply('查询失败,请稍后再试');
}