'Sending a Direct Message using Twitter API using Twitter Lib from Google App Script

I am trying to send direct message through twitter api using Twitter-Lib through App-Script. Below is the definition of sendMsg fucntion

function sendMsg(user, tweet) {
  var twitterKeys = {
    TWITTER_CONSUMER_KEY: "<<>>",
    TWITTER_CONSUMER_SECRET: "<<>>",
    TWITTER_ACCESS_TOKEN: "<<>>",
    TWITTER_ACCESS_SECRET: "<<>>",

 }
  
  var props = PropertiesService.getScriptProperties();
  // props.deleteAllProperties()
  props.setProperties(twitterKeys);
  var service = new Twitterlib.OAuth(props);
  
  if ( service.hasAccess() ) {          
        var user_id = '77773855';
        var dm_link = 'https://api.twitter.com/1.1/direct_messages/events/new.json'
        var response = service.fetch(dm_link, {
            method: "POST",
            muteHttpExceptions: true,
            data: {"event": 
                        {"type": "message_create", 
                        "message_create": {
                            "target": {"recipient_id": user_id}, 
                            "message_data": {"text": "Hello"}
                            }
                          }
                    }
        });
    console.log(response.getResponseCode())
  }  
}

But when I execute this code, the response is always empty and response.getResponseCode() returns 422. Any leads on what I am doing wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source