npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@core-workspace/infoflow-sdk-nodejs

v0.1.5

Published

InfoFlow SDK for Node.js - 企业即时通讯开放平台 SDK

Downloads

559

Readme

InfoFlow SDK for Node.js

npm version License: MIT

企业即时通讯开放平台 Node.js SDK,提供消息发送和实时事件接收能力。

核心特性

  • WebSocket 长连接:实时接收消息推送,自动心跳保活、断线重连
  • 多层级事件分发:支持按消息类型、聊天类型、精确匹配等多种订阅方式
  • 消息管理:支持发送、撤回、置顶单聊和群聊消息
  • 群聊管理:完整的群生命周期管理,包括创建、解散、成员管理、群设置等

安装与版本管理

# 安装
npm install @core-workspace/infoflow-sdk-nodejs

# 更新到最新版本
npm update @core-workspace/infoflow-sdk-nodejs

环境要求: Node.js >= 16.0.0

本项目遵循 语义化版本 规范。

快速开始

import { WSClient, Client, LogLevel } from '@core-workspace/infoflow-sdk-nodejs';

// ========== WebSocket 事件接收 ==========

const wsClient = new WSClient({
  appId: 'your-app-id',
  appSecret: 'your-app-secret',
});

// 注册事件处理器
wsClient.on('private.text', async (event) => {
  // 从原始数据获取字段
  const { raw } = event.data;
  console.log('私聊文本:', raw.Content);
  console.log('发送者:', raw.FromUserName);
});

wsClient.on('group.text', async (event) => {
  console.log('群聊文本:', event.data.raw.message.body);
});

wsClient.on('group.event.member_add', async (event) => {
  console.log('新成员加入群:', event.data.groupId);
});

// 建立连接
await wsClient.connect();

// ========== REST API 消息发送 ==========

const client = new Client({
  appId: 'your-app-id',
  appSecret: 'your-app-secret',
  agentId: 'your-agent-id',
});

// 发送消息
await client.im.message.sendToUser('[email protected]', '你好!');
await client.im.message.sendToGroup(12345, '大家好!');

事件路由

SDK 支持多层级事件路由,一条消息会触发所有匹配的处理器:

私聊文本消息触发:private.text → text → private.* → *
群聊图片消息触发:group.image → image → group.* → *

事件路由表

私聊消息路由

| 事件名 | 常量 | 说明 | |--------|------|------| | private.text | PrivateMessageTypes.TEXT | 私聊文本消息 | | private.image | PrivateMessageTypes.IMAGE | 私聊图片消息 | | private.file | PrivateMessageTypes.FILE | 私聊文件消息 | | private.richtext | PrivateMessageTypes.RICHTEXT | 私聊富文本消息 | | private.markdown | PrivateMessageTypes.MARKDOWN | 私聊Markdown消息 | | private.* | ChatTypePatterns.PRIVATE_ALL | 所有私聊消息 |

群聊消息路由

| 事件名 | 常量 | 说明 | |--------|------|------| | group.text | GroupMessageTypes.TEXT | 群聊文本消息 | | group.image | GroupMessageTypes.IMAGE | 群聊图片消息 | | group.file | GroupMessageTypes.FILE | 群聊文件消息 | | group.richtext | GroupMessageTypes.RICHTEXT | 群聊富文本消息 | | group.markdown | GroupMessageTypes.MARKDOWN | 群聊Markdown消息 | | group.mixed | GroupMessageTypes.MIXED | 群聊混合消息 | | group.* | ChatTypePatterns.GROUP_ALL | 所有群聊消息 |

群聊系统事件路由

| 事件名 | 常量 | 说明 | |--------|------|------| | group.event.member_add | GroupSystemEventRoutes.MEMBER_ADD | 群成员加入 | | group.event.member_del | GroupSystemEventRoutes.MEMBER_DEL | 群成员退出 | | group.event.manager_add | GroupSystemEventRoutes.MANAGER_ADD | 新增群管理员 | | group.event.manager_del | GroupSystemEventRoutes.MANAGER_DEL | 取消群管理员 | | group.event.open_app | GroupSystemEventRoutes.OPEN_APP | 添加机器人 | | group.event.close_app | GroupSystemEventRoutes.CLOSE_APP | 移除机器人 | | group.event.menu_click | GroupSystemEventRoutes.MENU_CLICK | 点击菜单气泡 | | group.event.emoji_reply_add | GroupSystemEventRoutes.EMOJI_REPLY_ADD | 添加表情回复 | | group.event.emoji_reply_delete | GroupSystemEventRoutes.EMOJI_REPLY_DELETE | 删除表情回复 | | group.event.* | ChatTypePatterns.GROUP_EVENT_ALL | 所有群系统事件 |

注意group.* 仅匹配群聊消息,不包含群系统事件。群系统事件使用 group.event.* 匹配。

按消息类型路由(不区分私聊/群聊)

| 事件名 | 常量 | 说明 | |--------|------|------| | text | MessageTypes.TEXT | 所有文本消息 | | image | MessageTypes.IMAGE | 所有图片消息 | | file | MessageTypes.FILE | 所有文件消息 | | richtext | MessageTypes.RICHTEXT | 所有富文本消息 | | markdown | MessageTypes.MARKDOWN | 所有Markdown消息 | | mixed | MessageTypes.MIXED | 所有混合消息(仅群聊) |

通配符路由

| 事件名 | 常量 | 说明 | |--------|------|------| | private.* | ChatTypePatterns.PRIVATE_ALL | 所有私聊消息 | | group.* | ChatTypePatterns.GROUP_ALL | 所有群聊消息 | | group.event.* | ChatTypePatterns.GROUP_EVENT_ALL | 所有群系统事件 | | * | ChatTypePatterns.ALL | 所有事件 |

支持的消息类型

| msgType | 说明 | 私聊 | 群聊 | |---------|------|------|------| | text | 纯文本 | ✅ | ✅ | | image | 图片 | ✅ | ✅ | | file | 文件 | ✅ | ✅ | | richtext | 富文本 | ✅ | ✅ | | markdown | Markdown | ✅ | ✅ | | mixed | 混合消息 | ❌ | ✅ |

事件数据结构

SDK 仅解析核心字段用于路由,原始数据完整保留在 raw 字段中:

// 消息事件
interface NormalizedEventData {
  chatType: 'private' | 'group';  // 聊天类型
  msgType: string;                 // 消息类型
  raw: any;                        // 完整原始 payload
}

// 群聊系统事件
interface NormalizedGroupEventData {
  chatType: 'group';
  eventType: string;      // GROUP_MEMBER_ADD, GROUP_OPEN_APP, ...
  groupId: number;
  payload: any;           // 原始数据
}

从原始数据获取字段

// 私聊消息
wsClient.on('private.image', async (event) => {
  const { raw } = event.data;
  console.log('发送者:', raw.FromUserName);
  console.log('发送者ID:', raw.FromUserId);
  console.log('图片URL:', raw.PicUrl);
  console.log('消息ID:', raw.MsgId);
});

// 群聊消息
wsClient.on('group.mixed', async (event) => {
  const { raw } = event.data;
  console.log('群ID:', raw.groupid);
  console.log('发送者ID:', raw.message.header.fromuserid);
  console.log('消息体:', raw.message.body);
});

// 通配符处理
wsClient.on('*', async (event) => {
  if (!event.data.chatType) {
    console.log('连接事件:', event.type);
    return;
  }
  console.log('消息:', event.data.msgType, event.data.raw);
});

连接事件

wsClient.on('connected', (event) => console.log('已连接:', event.data.connectionId));
wsClient.on('disconnected', (event) => console.log('断开:', event.data.reason));
wsClient.on('error', (event) => console.error('错误:', event.data.error));

消息发送

创建 Client

import { Client, LogLevel } from '@core-workspace/infoflow-sdk-nodejs';

const client = new Client({
  appId: 'your-app-id',
  appSecret: 'your-app-secret',
  agentId: 'your-agent-id',
  baseUrl: 'https://apiin.im.baidu.com/api/v1',  // 可选
  loggerLevel: LogLevel.Info,                     // 可选
});

发送消息

// 单聊文本
await client.im.message.sendToUser('[email protected]', '你好!');

// 单聊 Markdown
await client.im.message.sendToUser('[email protected]', { content: '# 标题' }, 'md');

// 多用户(用 | 分隔)
await client.im.message.sendToUser('[email protected]|[email protected]', '群发');

// 群聊文本
await client.im.message.sendToGroup(12345, '大家好!');

// 群聊 Markdown
await client.im.message.sendToGroup(12345, '# 公告', 'MD');

// 群聊带 @人
await client.im.message.sendToGroupWithOptions({
  groupId: 12345,
  msgtype: 'TEXT',
  body: [
    { type: 'TEXT', content: '请注意 ' },
    { type: 'AT', atall: true }
  ]
});

撤回消息

// 撤回单聊消息
const result = await client.im.message.sendToUser('user', '你好');
await client.im.message.revokeFromUser(result.msgkey, agentId);

// 撤回群聊消息
const groupResult = await client.im.message.sendToGroup(12345, '测试');
await client.im.message.revokeFromGroup(12345, groupResult.messageid, groupResult.msgseqid);

消息置顶与获取

// 置顶群消息
await client.im.message.pinMessage({
  groupId: 12345,
  msgId: '1825540504875551808',
  opType: 1  // 1-置顶,2-取消置顶
});

// 获取消息内容
const msg = await client.im.message.getMessage({
  fromId: 'zhangsan',
  receiverId: 12345,      // 群ID或agentId
  receiverType: 2,        // 2-群聊,7-单聊
  msgId: '1825540504875551808'
});

消息类型

| 场景 | 类型 | 内容格式 | |------|------|----------| | 单聊 | text(默认)、mdimagerichtext | 字符串或 { content: string } | | 群聊 | TEXT(默认)、MDIMAGE | 字符串 |

群聊管理

群生命周期

// 创建群聊
const group = await client.im.group.create({
  groupName: '项目组',
  groupOwner: '[email protected]',
  memberList: ['[email protected]', '[email protected]'],
});

// 修改群名称
await client.im.group.updateName(group.groupId, '新群名');

// 解散群聊
await client.im.group.disband(group.groupId, '[email protected]');

成员管理

// 获取群成员
const members = await client.im.group.getMembers(12345);

// 添加成员
await client.im.group.addMembers(12345, ['[email protected]', '[email protected]']);

// 移除成员
await client.im.group.removeMembers(12345, ['[email protected]']);

// 设置群管理员
await client.im.group.setManagers(12345, ['[email protected]']);

// 修改成员备注(需机器人是管理员)
await client.im.group.modifyUserRemark({
  toUserId: 'zhangsan',
  groupId: 12345,
  remark: '产品经理'
});

群设置

// 更新群公告
await client.im.group.updateBulletin(12345, '新公告内容');

// 添加群标签页
await client.im.group.addTab({
  groupId: 12345,
  name: '项目看板',
  url: 'https://example.com/board'
});

// 更新群菜单可见性
await client.im.group.updateMenuVisible({
  groupId: 12345,
  operationType: 'show',
  mainMenuKeys: ['key_1012']
});

// 修改群侧边栏(需机器人是管理员)
await client.im.group.updateSidebar({
  groupId: 12345,
  sidebarLink: 'https://example.com/sidebar',
  autoOpen: 1,
  customSidebar: 1
});

核心模块

WSClient

const wsClient = new WSClient({
  appId: string,        // 必填:应用 ID
  appSecret: string,    // 必填:应用密钥
  baseUrl?: string,     // API 基础 URL,默认 https://apiin.im.baidu.com
  wsGateway?: string,   // WebSocket Gateway 地址
  heartbeatInterval?: number,  // 心跳间隔(毫秒),默认 120000
  autoAck?: boolean,    // 是否自动发送 ACK,默认 true
  logger?: Logger,      // 自定义日志器
});

await wsClient.connect();
wsClient.disconnect();
wsClient.on(event, callback);
wsClient.off(event, callback);

Client

const client = new Client({
  appId: string,        // 必填:应用 ID
  appSecret: string,    // 必填:应用密钥
  agentId: string,      // 必填:Agent ID
  baseUrl?: string,     // API 基础 URL,默认 https://apiin.im.baidu.com/api/v1
  loggerLevel?: LogLevel,  // 日志级别,默认 Info
});

// Token 管理
client.getTokenManager().getAccessToken();

支持的 API 列表

消息管理 client.im.message

| 方法 | 说明 | |------|------| | sendToUser(userId, content, msgType?) | 发送单聊消息 | | sendToGroup(groupId, content, msgType?) | 发送群聊消息 | | sendToGroupWithOptions(options) | 发送群聊消息(高级选项,支持@人) | | revokeFromUser(msgkey, agentId) | 撤回单聊消息 | | revokeFromGroup(groupId, msgId, msgSeqId) | 撤回群聊消息 | | pinMessage(options) | 群消息置顶/取消置顶 | | getMessage(options) | 获取指定消息内容 |

群聊管理 client.im.group

| 方法 | 说明 | |------|------| | create(options) | 创建群聊 | | updateName(groupId, name) | 修改群名称 | | disband(groupId, groupOwner) | 解散群聊 | | getMembers(groupId) | 获取群成员列表 | | addMembers(groupId, memberList, agentIdList?) | 添加群成员 | | removeMembers(groupId, memberList, agentIdList?) | 移除群成员 | | setManagers(groupId, userEmails?, robotAgentIds?) | 设置群管理员 | | updateBulletin(groupId, bulletin) | 更新群公告 | | modifyUserRemark(options) | 修改群成员备注 | | addTab(options) | 添加群标签页 | | updateMenuVisible(options) | 更新群菜单可见性 | | supportAuth(groupId) | 机器人群授权 | | cancelAuth(groupId) | 取消机器人群授权 | | updateSidebar(options) | 修改群侧边栏 |

EventDispatcher

import { EventDispatcher, Logger, LogLevel } from '@core-workspace/infoflow-sdk-nodejs';

const dispatcher = new EventDispatcher(new Logger('MyApp', LogLevel.Info));

dispatcher.on('text', async (event) => { ... });
dispatcher.on('private.text', async (event) => { ... });
dispatcher.off('text', callback);
dispatcher.removeAllHandlers();

Logger

import { Logger, LogLevel } from '@core-workspace/infoflow-sdk-nodejs';

const logger = new Logger('MyApp', LogLevel.Debug);
// LogLevel.Debug | Info | Warn | Error

Webhook 模式

⚠️ Webhook 模式暂不支持,建设中。建议使用 WebSocket 长连接模式接收事件。

测试

# 配置环境变量
cat > .env << EOF
INFOFLOW_APP_ID=your_app_id
INFOFLOW_APP_SECRET=your_app_secret
INFOFLOW_AGENT_ID=your_agent_id
INFOFLOW_TEST_USER=your_test_user
EOF

# REST API 测试
node examples/rest-api-demo.mjs

# WebSocket 事件接收测试
node examples/ws-event-receiver.mjs

License

MIT