如何关联Twilio Programmable Chat前后端消息以展示ReadAt元数据?
解决Twilio Programmable Chat消息关联问题的方案
我之前也碰到过这个棘手的问题,核心就是要在前端发送消息时给消息加一个双方都能拿到的唯一标识,以此关联Webhook和前端messageAdded事件里的消息。这里有两个可行的方案,优先推荐第一个:
方案1:自定义唯一标识(Attributes)(最可靠)
这是官方推荐的思路,通过给消息添加自定义属性,让前端和Webhook共享同一个关联ID,完美解决匹配问题。
具体步骤:
前端生成唯一ID并携带发送
用标准UUID库生成一个唯一标识,发送消息时把它塞进attributes字段:import { v4 as uuidv4 } from 'uuid'; // 生成全局唯一的关联ID const correlationId = uuidv4(); // 发送消息时带上自定义属性 channel.sendMessage({ body: "Hey there!", attributes: { correlationId: correlationId } });Webhook(preMessageSend)中提取关联ID
在你的Webhook接收端,可以从请求体的Attributes里拿到这个ID,直接和消息数据一起存入数据库:// 示例:Node.js处理Webhook app.post('/twilio/pre-message-send', (req, res) => { const messageAttributes = JSON.parse(req.body.Attributes); const correlationId = messageAttributes.correlationId; // 把关联ID和消息内容、发送者等数据绑定存入数据库 saveToDatabase({ correlationId, body: req.body.Body, sender: req.body.From, // 其他需要存储的字段 }); // 返回Twilio要求的空响应即可 res.send({}); });前端messageAdded事件中匹配并更新
当消息被Twilio确认并推送到前端时,从消息对象里取出关联ID,然后调用你的后端接口,把Twilio生成的官方messageId(也就是sid)更新到数据库的对应记录中:channel.on('messageAdded', (message) => { const correlationId = message.attributes.correlationId; const twilioMessageId = message.sid; // 调用后端接口更新数据库记录 fetch('/api/update-message-sid', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ correlationId, twilioMessageId }) }); });
方案2:通过消息特征组合匹配(不推荐)
如果因为某些限制不能用自定义属性,可以尝试用发送者ID、消息内容、发送时间戳的组合来匹配,但这个方法有明显缺陷:如果同一用户在同一毫秒发送了相同内容的消息,就会出现匹配错误,仅作为备选方案。
大致步骤:
前端发送时记录特征数据
const sendTimestamp = Date.now(); const messageBody = "Hey there!"; const senderId = currentUser.identity; channel.sendMessage({ body: messageBody }).then(() => { // 临时存储这些特征,等待messageAdded事件触发 localStorage.setItem(`temp-message-${sendTimestamp}`, JSON.stringify({ senderId, messageBody, sendTimestamp })); });Webhook中记录对应特征
app.post('/twilio/pre-message-send', (req, res) => { const senderId = req.body.From; const messageBody = req.body.Body; const createdTimestamp = new Date(req.body.DateCreated).getTime(); saveToDatabase({ senderId, messageBody, createdTimestamp }); res.send({}); });前端messageAdded事件中匹配特征
channel.on('messageAdded', (message) => { const senderId = message.author; const messageBody = message.body; const createdTimestamp = new Date(message.dateCreated).getTime(); // 调用后端接口,用特征组合查找对应的数据库记录 fetch('/api/find-message-by-features', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ senderId, messageBody, createdTimestamp }) }).then(res => res.json()).then(record => { // 更新记录的twilioMessageId }); });
再次强调:这个方法容错率极低,除非万不得已,否则优先用方案1。
内容的提问来源于stack exchange,提问作者Jinal Shah
相关产品推荐
相关产品推荐

