Twitter API provides us with various end-points for creating tweets, searching tweets or sending direct messages. Today, we will be exploring one such end-point, POST direct_messages/events/new (message_create)
It allows us to send direct messages to our application’s users by using their Twitter ID’s and can be easily integrated into our application.
Wait, but what are the requirements?
To start working with Twitter APIs, you need to have a twitter developer account and an app in this account. So, if you guys don’t have one, you’ll have to begin with that.
You can refer to below article for help,
Once you create Twitter Developer Account, you will get access to API Key, API Secret, Access token and Access Secret. These will be required to make our API Call. (Take a note of these as Access token and Secret are only visible once and will have to be regenerated if lost)
Now, moving back to our topic…
Resource URL:
The URL for the direct message end-point. We will be using this for sending our requests to the Twitter API.
Making API call with Node.js:
Creating an event object:
We have to specify the following parameters in the event object:
- type (required) : The type of event you are posting. For direct messages, use message_create .
- message_create.target.recipient_id : Twitter ID of the user who should receive the direct message.
- message_create.message_data : It defines the content to be delivered to the recipient.
Creating Message Data Object:
- text (required) : Text of our direct message. Maximum allowed length is 10,000 characters.
- attachment.type (optional) : The attachment type. Can be media or location.
- quick_reply.type (optional) : It presents the user with quick reply options which can be an array of values, text inputs, or location object.
Here is a code snippet for sample event object -
Authorization Headers:
For authorization, Twitter uses OAuth 1.0 . To authenticate our request, we will have to specify the following parameters in authorization header:
- oauth_consumer_key : API key obtained from twitter developer account
- oauth_nonce : Random 32-bit string, uniquely generated for each request
- oauth_signature : Oauth signature generated as a function of API key, API secret, Access token, Token secret, Nonce and Timestamp. For more details, check out -
https://developer.twitter.com/en/docs/authentication/oauth-1-0a/creating-a-signature
- oauth_signature_method : ‘HMAC-SHA1’
- oauth_timestamp : Automatically generated timestamp
- oauth_token : Access token obtained from developer account
- oauth_version : “1.0”
Example Request:
Finally, we need to send the event object generated in the above steps with proper authorization headers via POST method. Below is an example request to demonstrate the same :
Example Response:
Thankyou!
References: