How to fetch Airtable records in Twilio Autopilot and display data to users?

I’m working with Twilio Autopilot and need help with data retrieval. My bot uses a Collect action to get a date input from users (like Feb 15, 2019). After getting this date, I want to query my Airtable database to find the matching record and show the results back to the user.

The response should be something like “on Feb 15 the Cinema A is showing this film, Cinema B is showing that movie”.

I have this code for connecting to Airtable but I’m stuck on how to extract the returned information and use it in my response:

exports.handler = function(context, event, callback) {
    var AirtableAPI = require('airtable');
    var database = new AirtableAPI({apiKey: 'my_api_key'}).base('my_base_id');
    
    database('Schedule').find('rec123ABC456DEF', function(error, data) {
        if (error) { 
            console.error(error); 
            return; 
        }
        console.log(data);
    });
}

The Airtable response looks like this:

{
    "id": "rec123ABC456DEF",
    "fields": {
        "Date": "2019-02-15",
        "Cinema A": "Iron Man",
        "Cinema B": "Spider-Man"
    },
    "createdTime": "2019-02-15T18:30:22.000Z"
}

How can I extract the field values and pass them back to the user through Autopilot?

just grab the fields in your callback, like let cinemaA = data.fields['Cinema A'] and let cinemaB = data.fields['Cinema B']. then create your response using those variables and send it back to Autopilot!

You need to properly structure your callback function to return the response to Autopilot. After extracting the field values as mentioned, you should construct a Twilio response object. Here’s what your handler should look like:

exports.handler = function(context, event, callback) {
    var AirtableAPI = require('airtable');
    var database = new AirtableAPI({apiKey: 'my_api_key'}).base('my_base_id');
    
    database('Schedule').find('rec123ABC456DEF', function(error, data) {
        if (error) { 
            console.error(error);
            callback(error);
            return; 
        }
        
        const cinemaA = data.fields['Cinema A'];
        const cinemaB = data.fields['Cinema B'];
        const date = data.fields['Date'];
        
        const responseMessage = `On ${date}, Cinema A is showing ${cinemaA}, Cinema B is showing ${cinemaB}`;
        
        callback(null, {
            actions: [{
                say: responseMessage
            }]
        });
    });
}

The key part is using the callback function with the proper Autopilot response format containing the actions array.