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

求助:如何在Fulfillment的index.js中用Twilio发送含pickupLocation的短信?

Troubleshooting Twilio SMS Sending in Dialogflow Fulfillment (index.js)

Let’s walk through the most common pitfalls and fix your SMS sending function step by step. Since you mentioned you’ve got a function already but it’s failing, I’ll start with a production-ready, Dialogflow-specific example, then break down key syntax issues to check against your code.

First, Confirm Prerequisites

Before diving into code, make sure these boxes are checked:

  • You have a Twilio account with an active SMS-enabled phone number
  • You’ve installed the Twilio Node.js library in your fulfillment project: npm install twilio
  • You’ve stored Twilio credentials (Account SID, Auth Token, phone number) as environment variables (never hardcode sensitive data!)

Working Code Example

Here’s a complete, tested snippet that fits into the standard Dialogflow Fulfillment index.js structure, designed to send the user’s pickupLocation via SMS:

const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');
const twilio = require('twilio');

// Initialize Twilio client with environment variables
const twilioClient = twilio(
  functions.config().twilio.account_sid,
  functions.config().twilio.auth_token
);
const TWILIO_PHONE = functions.config().twilio.phone_number;
const RECIPIENT_PHONE = '+1234567890'; // Replace with your target number, or pull from user data

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((req, res) => {
  const agent = new WebhookClient({ request: req, response: res });

  // Async function to handle SMS sending
  async function sendPickupSMS(agent) {
    try {
      // Extract pickup location from Dialogflow intent parameters
      const pickupLocation = agent.parameters.pickupLocation;
      if (!pickupLocation) {
        agent.add("I didn't catch your pickup location—could you repeat that?");
        return;
      }

      // Send SMS via Twilio API
      const smsResponse = await twilioClient.messages.create({
        body: `New pickup request: ${pickupLocation}`,
        from: TWILIO_PHONE,
        to: RECIPIENT_PHONE
      });

      // Confirm success to the user
      agent.add(`Got it! I've sent your pickup location (${pickupLocation}) to the team via SMS.`);
      console.log(`SMS sent successfully. SID: ${smsResponse.sid}`);
    } catch (error) {
      // Handle errors gracefully
      console.error('SMS sending failed:', error);
      agent.add("Sorry, I couldn't send your pickup location right now. Please try again later.");
    }
  }

  // Map your Dialogflow intent to the function
  const intentMap = new Map();
  intentMap.set('SendPickupLocationIntent', sendPickupSMS); // Replace with your intent name
  agent.handleRequest(intentMap);
});

Key Syntax & Common Fixes for Your Code

  1. Async/Await is Mandatory: Twilio’s messages.create() returns a promise—your function must be async, and you need to await the API call. Forgetting this leads to silent failures because the fulfillment finishes before the SMS request completes.
  2. Environment Variables Setup: Set your Twilio credentials in Firebase with this command (run in your project root):
    firebase functions:config:set twilio.account_sid="YOUR_SID" twilio.auth_token="YOUR_TOKEN" twilio.phone_number="YOUR_TWILIO_NUMBER"
    
  3. Parameter Name Match: Double-check that agent.parameters.pickupLocation exactly matches the parameter name defined in your Dialogflow intent. Typos here mean you’ll send empty or undefined data.
  4. E.164 Phone Format: Both from and to numbers must use E.164 format (e.g., +1234567890). Missing the country code will cause Twilio to reject the request.
  5. Error Handling: Always wrap the Twilio call in a try/catch block. This catches issues like invalid credentials, insufficient Twilio balance, or blocked numbers, and lets you inform the user instead of crashing the fulfillment.

If You’re Still Stuck

Share your specific code snippet (redact credentials!) and any error messages from the Firebase Functions logs. Common issues to look for in logs:

  • Authentication errors (invalid SID/token)
  • Missing or undefined pickupLocation parameter
  • Twilio API error codes (e.g., 21211 for an invalid phone number)

内容的提问来源于stack exchange,提问作者Jeff G123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:17:25