消息上下文与发送能力

奶狗 发表于 4 周前 浏览 26 字数 1473 阅读时长 8分钟

3. 消息上下文与发送能力

ctx 由框架为每个消息构造(createContext),包含发送能力与机器人信息。

3.1 ctx.sendText(text)

await ctx.sendText('你好!');

内部处理:消息入库 → 调用 iLink 发送 → 更新状态 → 推送 SSE 事件。context_token 过期(-14)时自动从 DB 获取最新入站 token 重试一次。

3.2 ctx.sendMedia(filePath, mediaType, filename?, playtime?)

参数 说明
filePath 本地文件路径(需先把内容下载/生成到本地)
mediaType 'image' / 'video' / 'file' / 'voice'
filename file 类型需要,展示文件名
playtime 可选,秒数(voice 用)
await ctx.sendMedia('/tmp/photo.jpg', 'image');
await ctx.sendMedia('/tmp/report.pdf', 'file', '报告.pdf');
  • sendMedia 不会自动删除临时文件,插件发送后需自行清理(fs.unlinkSync)。
  • 不要用 'voice' 类型——微信客户端不渲染语音条、点不开。用 'file' 代替。
  • 图片类型会跳过缩略图生成,保持原图质量。

3.3 ctx.bot / ctx.msg

ctx.bot.id              // 机器人 ID
ctx.bot.bot_token       // 机器人 token
ctx.bot.base_url        // iLink 基础地址
ctx.bot.user_id         // 所属账号 ID

ctx.msg.content         // 消息文本(已解密)
ctx.msg.peer_id         // 会话 ID(如 o9cq802Ep_xxxx@im.wechat 或 QQ 群 peer)
ctx.msg.context_token   // 上下文票据(用于回复)
ctx.msg.msg_type        // 消息类型:text/image/voice/video/file
ctx.msg.group_id        // 群 ID(群消息非空,私聊为空)
ctx.msg.user_id         // 发送者用户 ID
ctx.msg.sender_info     // 发送者信息(含昵称等,QQ 群被动识别成员时可用)

3.4 主动调用智能助手做 AI 生成(callAssistant)

插件也能主动调 AI 做文本生成:

const plugins = require('../../lib/plugins');

const reply = await plugins.callAssistant({
  botId: ctx.bot.id,
  userId: ctx.bot.user_id,
  prompt: '把以下数据用口语总结成一段话:\n' + JSON.stringify(rawData),
});

await ctx.sendText(reply);
参数 必填 说明
botId 机器人 ID
prompt 发给 AI 的内容
userId 推荐 用于扣减 Token 额度;不传则不扣(可能绕过配额)
systemPrompt 覆盖默认系统提示词
history [{role, content}] 多轮上下文
maxTokens 最大生成 token 数
temperature 温度参数(0-2)
tools OpenAI function 工具定义,启用 function calling
toolHandler async (name, args) => string,配合 tools 使用

务必传入 userId,让用量纳入统计,避免被滥用。调用失败会抛 Error,请用 try/catch 包裹。