UCWA消息处理异常:获取Incoming消息href时出现undefined错误
Let's break down the issue you're facing and fix the code step by step. The core problem here is a combination of unlinked variables and missing safety checks for nested data structures in the UCWA Event API response.
What's Going Wrong
Your console.log(messageIn) shows the expected resources, but the subsequent code tries to use link and embed variables that aren't connected to the messageIn array you built. Additionally, you're accessing nested properties without verifying they exist first—this is why you're hitting the undefined error when checking embed.message.direction.
Fixed Code Example
Here's the adjusted code with key fixes and safety checks:
SkypeService.getEvent(msg).then(function (result) { msg.eventsNext = result._links.next.href; if (result && result.sender && result.sender.length > 0) { for (var item in result.sender) { var ref = result.sender[item].events; for (var key in ref) { // Push the full event object (not just _embedded) to keep _links context messageIn.push(ref[key]); } } } console.log(messageIn); // Iterate through collected events to find incoming messages messageIn.forEach(function(event) { // First confirm the event is a message type if (event._links && event._links.rel === 'message') { console.log("message is there"); // Check if the embedded message exists before accessing it if (event._embedded && event._embedded.message) { console.log("links exist"); var incomingMessage = event._embedded.message; // Verify direction exists before checking its value if (incomingMessage.direction && incomingMessage.direction === "Incoming") { console.log("direction is there"); // Use optional chaining to safely access nested hrefs msg.participant = incomingMessage._links.participant?.href; msg.contMsg = incomingMessage._links.messaging?.href; msg.msgIn = incomingMessage._links.plainMessage?.href; } } } }); });
Key Fixes Explained
Link Variables to Collected Events
The original code pushed only_embeddeddata tomessageInand then referenced undefinedlink/embedvariables. We now push the full event object and iterate throughmessageInto access each event's_linksand_embeddedproperties directly.Add Safety Checks for Nested Properties
UCWA responses may have missing nested fields depending on the event type. We added checks forevent._links,event._embedded.message, andincomingMessage.directionto preventundefinederrors when accessing these properties.Use Optional Chaining for Robustness
The?.operator safely accesses nested hrefs—if a parent property like_links.participantdoesn't exist, it returnsundefinedinstead of throwing an error.Preserve Full Event Context
By pushing the complete event object tomessageIn, we retain the_linksdata needed to identify message-type events.
Since your conversation is already active (no accept href needed), this code will correctly capture the messaging and plainMessage hrefs you need to send a reply back to the Bot.
内容的提问来源于stack exchange,提问作者Heather

