UNPKG

node-red-contrib-feishu

Version:

Node-RED节点用于发送飞书消息

126 lines (118 loc) 4.93 kB
/** * 飞书机器人节点模块 * 该模块实现了一个Node-RED节点,用于向飞书机器人发送消息 * 支持发送纯文本和富文本两种类型的消息 * * @module node-red-contrib-feishu * @requires axios */ /** * Node-RED节点主函数 * @param {Object} RED - Node-RED运行时实例 */ module.exports = function(RED) { /** * 飞书节点构造函数 * @class FeishuNode * @param {Object} config - 节点配置对象 * @param {string} [config.name] - 节点名称 * @param {string} config.webhookUrl - 飞书机器人的Webhook URL * @param {string} [config.messageType=text] - 消息类型,支持text和rich_text */ function FeishuNode(config) { // 创建节点实例,继承Node-RED节点的基本功能 RED.nodes.createNode(this, config); const node = this; // 引入axios用于发送HTTP请求 const axios = require('axios'); /** * 处理输入消息事件 * 当节点收到上游数据时触发 * @param {Object} msg - 输入消息对象 */ node.on('input', async function(msg) { // 获取配置参数,支持通过msg动态覆盖配置 const webhookUrl = config.webhookUrl || msg.webhookUrl; const messageType = config.messageType || msg.messageType || 'text'; let content = msg.payload; // 验证必要参数 if (!webhookUrl) { node.error('Webhook URL is required'); return; } try { // 根据消息类型构建不同格式的消息内容 let messageContent; if (messageType === 'text') { // 构建纯文本消息格式 messageContent = { msg_type: 'text', content: { // 如果content不是字符串,则转换为JSON字符串 text: typeof content === 'string' ? content : JSON.stringify(content) } }; } else if (messageType === 'rich_text') { // 构建富文本消息格式 messageContent = { msg_type: 'post', content: { post: { zh_cn: { title: msg.title || '', // 支持数组格式的富文本内容,如果不是数组则转换为标准格式 content: Array.isArray(content) ? content : [[{ tag: 'text', text: typeof content === 'string' ? content : JSON.stringify(content) }]] } } } }; } // 发送HTTP POST请求到飞书机器人webhook地址 const response = await axios.post(webhookUrl, messageContent); // 处理响应结果 if (response.data.code === 0) { // 发送成功,设置节点状态为绿色 node.status({fill: 'green', shape: 'dot', text: '发送成功'}); msg.payload = response.data; node.send(msg); } else { // 业务层面的错误 throw new Error(response.data.msg || '发送失败'); } } catch (error) { // 发送失败,设置节点状态为红色 node.status({fill: 'red', shape: 'ring', text: '发送失败'}); node.error(error.message, msg); } }); /** * 节点关闭事件处理 * 清除节点状态 */ node.on('close', function() { node.status({}); }); } // 注册节点类型 RED.nodes.registerType('feishu', FeishuNode, { // 节点默认配置 defaults: { name: {value: ''}, // 节点名称 webhookUrl: {value: '', required: true}, // 必填的webhook地址 messageType: {value: 'text'} // 默认使用text类型 }, category: 'social', // 节点分类 color: '#a6bbcf', // 节点颜色 inputs: 1, // 输入连接点数量 outputs: 1, // 输出连接点数量 icon: 'font-awesome/fa-paper-plane-o', // 节点图标 // 节点标签显示函数 label: function() { return this.name || '飞书消息'; }, paletteLabel: '飞书消息' // 面板中显示的节点名称 }); }