Cloud function - Twilio SDK or REST API

I need to send SMS via Twilio and iā€™ve tried 2 things so far. First I was hoping the NodeJS SDK would be allowed to require, but it appears that is isnā€™t considered a ā€œwhitelistedā€ plugin (you might want to consider that.

Next Iā€™ve tried to use the Moralis.Cloud.httpRequest and try and use the standard REST APIs from Twilio. This doesnā€™t seem to run. Here is my code. I canā€™t seem to get any logs to print so I feel as if itā€™s not running, but i canā€™t figure out why.

Moralis.Cloud.define("test", async (request) => {
const web3 = Moralis.web3ByChain("0x3"); // Ropsten
const abi = Moralis.Web3.abis.erc20;
const address = "0x484f56061DFD2166754b572913C822E9BD19d513";
const contract = new web3.eth.Contract(abi, address);
const ethAddy = await request.user.get("ethAddress");
//Get balance of the user calling the functions
const balance = await contract.methods
.balanceOf(ethAddy)
.call();
  
//send SMS
//*******This code doesn't work ********
const accountSid = 'XXX'; 
const authToken = 'XXX'; 
Moralis.Cloud.httpRequest({
  method: 'POST',
  url: 'https://api.twilio.com/2010-04-01/Accounts/'+accountSid+'/Messages.json',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Basic XXX'
  },
  form: {
    'Body': 'Yo yo',
    'To': '+111',
    'From': '+111'
  }
}).then(function(httpResponse) {
  console.log(httpResponse.text);
}, function(httpResponse) {
  console.error('Request failed with response code ' + httpResponse.status);
});
//**************************************

return ethAddy +" "+balance;
  
});

BTW - as a side noteā€¦the moralis-admin-cli wonā€™t work on my macOS. It seems to install but when I try to use it I get the error: command not found.

Hey first of all. console.log wonā€™t work on the server side .

You will need to use this for logging.

const logger = Moralis.Cloud.getLogger();
logger.info("Hello World"); 

And for the moralis-admin-cli I may have a solution.
I had this problem too. Please try this:

npx moralis-admin-cli [ā€¦]

Duh! I should have picked up on the logger issue, I was using the code samples in the moralis docs.

And for the moralis-admin-cli ----npx worked! Thanks!

3 Likes

Great to hear! Enjoy programming !

Were you able to get the Twilio REST API working @cvlsoft?

I would also like to know if thereā€™s a way to incorporate the Twilio sdk to be used.

This snippet is working for me. The key thing is to correctly BASE64 encode the credentials. Certainly it would be better to be able to use the standard Twilio client libraries, but for basic sending this approach with the REST API works.

function sendTwilioAlert(content) {
  const logger = Moralis.Cloud.getLogger();
  const SID = "XXXXXXXXXXXXXXXXXX";
  const auth = "XXXXXXXXXXXXXXXXX";
  let buff = new Buffer(`${SID}:${auth}`);
  let authCode = buff.toString("base64");
  logger.info(`Twilio authCode ${authCode}`);
  let data = {
    Body: content,
    MessagingServiceSid: "MESSEAGESID",
    To: "+15555551212,
  };
  Moralis.Cloud.httpRequest({
    method: "POST",
    url: "https://api.twilio.com/2010-04-01/Accounts/ZZZZZZZZZZZZZZ/Messages.js",
    body: data,
    headers: {
      Authorization: `BASIC ${authCode}`,
    },
  }).then(
    function (httpResp) {
      logger.info(httpResp.text);
    },
    function (httpResp) {
      logger.error(
        "Request failed with response code " +
          httpResp.status +
          "::" +
          httpResp.text
      );
    }
  );
}

@BJS Making Https calls to the twilio APIs are working fine for me. My question is whether I can use the twilio help library as I would like to use the cloud function of moralis to generate the access token from twilio.

Twilio has the helper libraries in node.js and would love to see if thatā€™s something that can be supported.

1 Like

Hey @waterglobal you canā€™t use external library in the cloud function directly. However, you can build a simple server to use the Twilio SDK and make it a REST API that can be called by the cloud function :raised_hands:

@YosephKS Understood, Iā€™ve actually started the process for that to have a simple server to do this. Thanks!

1 Like