Search code examples
twiliotwilio-functions

Online docs for getTwilioClient() as used in "Functions and Assets"


I have found a few examples of context.getTwilioClient(), but I have not been able to locate any online documentation. It's probably right under my nose, but it is eluding me. In particular, I'm trying to get information about workers in a Task Router queue (i.e., how many workers are in the different statuses and how many workers are available), but having the documentation will help with future projects.

I found some documentation saying that the context.getTwilioClient(), "enables you to invoke the getTwilioClient method on the context object for a fully-initialized Twilio REST API client." (https://support.twilio.com/hc/en-us/articles/115007737928-Getting-Started-with-Twilio-Functions)

It then shows this example, but there is no implementation of "messages" when I attempt to run this code:

var client = context.getTwilioClient();
client.messages.create({
  to: '+12025551212',
  from: '+12065551212',
  body: "hello world!"})

Thanks.


Solution

  • The messages property should be on the client. getTwilioClient returns the Twilio helper library for Node.js.

    I just created a Function with your code, and it worked as expected, meaning that I got the SMS, however, the function did time out because the callback was never invoked. To end the function invocation and respond to the caller, make sure you always invoke the callback function, like this:

    exports.handler = function(context, event, callback) {
      var client = context.getTwilioClient();
      client.messages.create({
        to: '+1xxxxxxxxxx',
        from: '+1xxxxxxxxxxx',
        body: "hello world!"})
      .then((message) => {
        console.log('SMS successfully sent');
        console.log(message.sid);
        // Make sure to only call `callback` once everything is finished, and to pass
        // null as the first parameter to signal successful execution.
        return callback(null, `Success! Message SID: ${message.sid}`);
      })
      .catch((error) => {
        console.error(error);
        return callback(error);
      });
    };
    

    You can learn more about the callback function here.

    If you still encounter this issue, can you tell use what Node Version you're using and which module dependencies and their versions?

    You can find these details at Settings & More > Dependencies in your Twilio Functions Service.