You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Node.js检测Sunshine平台的用户或会话ID是否已存在

实现方案

核心逻辑说明

我们需要在接收到用户发送的消息回调时,先查询当前会话的关联信息,判断该用户是否为首次在Sunshine平台发起会话:

  • 若会话中仅包含用户刚发送的1条消息,无历史交互记录,判定为新用户,推送欢迎消息
  • 若会话存在历史交互记录,判定为老用户,跳过推送

代码改造说明

  1. 新增SunshineConversationsApi.ConversationsApi实例,用于查询会话详情
  2. 实现check_conversation_ID_with_sunshine异步校验函数,新增新用户判定逻辑
  3. 调整webhook回调逻辑,增加await处理异步请求,避免时序异常

完整可运行代码

'use strict';
// 依赖引入
const express = require('express');
const bodyParser = require('body-parser');
const SunshineConversationsApi = require('sunshine-conversations-client');
// 配置项
let defaultClient = SunshineConversationsApi.ApiClient.instance;
let basicAuth = defaultClient.authentications['basicAuth'];
basicAuth.username = 'app_XXXXXXX';
basicAuth.password = 'XXXXXXXXXXXXXXXXX-bSwG85aM8qldJzTt4rgZlf_XQukWKE8ADMno85g';
const PORT = 5050;

const messagesApi = new SunshineConversationsApi.MessagesApi()
const conversationsApi = new SunshineConversationsApi.ConversationsApi()

// 服务端初始化
const app = express();
app.use(bodyParser.json());

// 暴露/messages接口接收webhook事件
app.post('/messages', async function(req, res) {
  const appId = req.body.app.id;
  const trigger = req.body.events[0].type;

  if (trigger === 'conversation:message') {
    const authorType = req.body.events[0].payload.message.author.type;
    if(authorType === 'user'){
      const conversationId = req.body.events[0].payload.conversation.id;
      // 执行新用户校验
      await check_conversation_ID_with_sunshine(appId,conversationId);
      res.end();
    }
  }
});

// 端口监听
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
});

// 会话存在性&新用户校验函数
async function check_conversation_ID_with_sunshine(appId, conversationId) {
  try {
    // 查询会话详情,包含消息列表
    const conversationRes = await conversationsApi.getConversation(appId, conversationId);
    const messages = conversationRes.conversation.messages;
    // 筛选用户发送的消息
    const userMessages = messages.filter(item => item.author.type === 'user');
    // 当用户仅发送过1条消息(当前触发回调的这条),判定为新用户
    if (userMessages.length === 1) {
      await sendMessage(appId, conversationId);
    }
  } catch (err) {
    console.error('会话查询异常:', err);
  }
}

// 发送欢迎消息函数
async function sendMessage(appId, conversationId){
  let messagePost = new SunshineConversationsApi.MessagePost();  
  messagePost.setAuthor({type: 'business'});
  // 替换为你预设的欢迎消息内容
  messagePost.setContent({type: 'text', text: '您好,欢迎咨询,请问有什么可以帮您的?'});
  await messagesApi.postMessage(appId, conversationId, messagePost);
}

注意事项

  • 你需要将配置项中的username和password替换为自己Sunshine平台的真实凭证
  • 欢迎消息内容可以根据业务需求自行修改,支持图片、卡片等多种消息类型
  • 生产环境建议添加日志埋点,方便排查推送异常问题

内容的提问来源于stack exchange,提问作者syed taha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 10:36:03