Module twitter

ballerinax/twitter Ballerina library

4.0.0

Overview

Twitter(X) is a widely-used social networking service provided by X Corp., enabling users to post and interact with messages known as "tweets".

The ballerinax/twitter package offers APIs to connect and interact with Twitter(X) API endpoints, specifically based on Twitter(X) API v2.

Setup guide

To use the Twitter connector, you must have access to the Twitter API through a Twitter developer account and a project under it. If you do not have a Twitter Developer account, you can sign up for one here.

Step 1: Create a Twitter Developer Project

  1. Open the Twitter Developer Portal.

  2. Click on the "Projects & Apps" tab and select an existing project or create a new one for which you want API Keys and Authentication Tokens.

    Twitter Developer Portal

Step 2: Set up user authentication settings

  1. Scroll down and Click on the Set up button to set up user authentication.

    Set up
  2. Complete the user authentication setup.

Step 3. Obtain Client Id and Client Secret.

  1. After completing the setup, you will be provided with your client Id and client secret. Make sure to save the provided client Id and client secret.

    Get Keys

Step 4: Setup OAuth 2.0 Flow

Before proceeding with the Quickstart, ensure you have obtained the Access Token using the following steps:

  1. Create an authorization URL using the following format:

    https://twitter.com/i/oauth2/authorize?response_type=code&client_id=<your_client_id>&redirect_uri=<your_redirect_uri>&scope=tweet.read%20tweet.write%20users.read%20follows.read&state=state&code_challenge=<your_code_challenge>&code_challenge_method=plain
    

    Replace <your_client_id>, <your_redirect_uri>, and <your_code_challenge> with your specific values. Make sure to include the necessary scopes depending on your use case.

    Note: The "code verifier" is a randomly generated string used to verify the authorization code, and the "code challenge" is derived from the code verifier. These methods enhance security during the authorization process. In OAuth 2.0 PKCE, there are two methods for creating a "code challenge":

    1. S256: The code challenge is a base64 URL-encoded SHA256 hash of a randomly generated string called the "code verifier".

    2. plain: The code challenge is the plain code verifier string itself.

    Example authorization URL:

    https://twitter.com/i/oauth2/authorize?response_type=code&client_id=asdasASDas21Y0OGR4bnUxSzA4c0k6MTpjaQ&redirect_uri=http://example&scope=tweet.read%20tweet.write%20users.read%20follows.read&state=state&code_challenge=D601XXCSK57UineGq62gUnsoasdas1GfKUY8QWhOF9hiN_k&code_challenge_method=plain
    

    Note: By default, the access token you create through the OAuth 2.0 Flow, as used here, will only remain valid for two hours. There is an alternative way that does not invalidate the access token after 2 hours. To do this, refer to Obtain access token under offline.access.

  2. Copy and paste the generated URL into your browser. This will redirect you to the Twitter authorization page.

    Authorize Page
  3. Once you authorize, you will be redirected to your specified redirect URI with an authorization code in the URL.

    Example:

    http://www.example.com/?state=state&code=QjAtYldxeTZITnd5N0FVN1B3MlliU29rb1hrdmFPUWNXSG5LX1hCRExaeFE3OjE3MTkzODMzNjkxNjQ6MTowOmFjOjE
    

    Note: Store the authorization code and use it promptly as it expires quickly.

  4. Use the obtained authorization code to run the following curl command, replacing <your_client_id>, <your_redirect_url>, <your_code_verifier>, and <your_authorization_code> with your specific values:

    • Linux/MacOS:
    Copy
    curl --location "https://api.twitter.com/2/oauth2/token" \
    --header "Content-Type: application/x-www-form-urlencoded" \
    --data-urlencode "code=<your_authorization_code>" \
    --data-urlencode "grant_type=authorization_code" \
    --data-urlencode "client_id=<your_client_id>" \
    --data-urlencode "redirect_uri=<your_redirect_url>" \
    --data-urlencode "code_verifier=<your_code_verifier>"
    • Windows:
    Copy
    curl --location "https://api.twitter.com/2/oauth2/token" ^
    --header "Content-Type: application/x-www-form-urlencoded" ^
    --data-urlencode "code=<your_authorization_code>" ^
    --data-urlencode "grant_type=authorization_code" ^
    --data-urlencode "client_id=<your_client_id>" ^
    --data-urlencode "redirect_uri=<your_redirect_url>" ^
    --data-urlencode "code_verifier=<your_code_verifier>"

    This command will return the access token necessary for API calls.

    Copy
    {
        "token_type":"bearer",
        "expires_in":7200,
        "access_token":"VWdEaEQ2eEdGdmVSbUJQV1U5LUdWREZuYndVT1JaNDddsdsfdsfdsxcvIZGMzblNjRGtvb3dGOjE3MTkzNzYwOTQ1MDQ6MTowOmF0Oj",
        "scope":"tweet.write users.read follows.read tweet.read"
    }
  5. Store the access token securely for use in your application.

Note: We recommend using the OAuth 2.0 Authorization Code with PKCE method as used here, but there is another way using OAuth 2.0 App Only OAuth 2.0 App Only. Refer to this document to check which operations in Twitter API v2 are done using which method: API reference.

Quickstart

To use the Twitter connector in your Ballerina application, update the .bal file as follows:

Step 1: Import the module

Import the twitter module.

Copy
import ballerinax/twitter;

Step 2: Instantiate a new connector

  1. Create a Config.toml file and, configure the obtained credentials in the above steps as follows:
Copy
token = "<Access Token>"
  1. Create a twitter:ConnectionConfig with the obtained access token and initialize the connector with it.
Copy
configurable string token = ?;

final twitter:Client twitter = check new({
    auth: {
        token
    }
});

Step 3: Invoke the connector operation

Now, utilize the available connector operations.

Post a tweet

Copy
public function main() returns error? {
    twitter:TweetCreateResponse postTweet = check twitter->/tweets.post( 
        payload = {
            text: "This is a sample tweet"
        }
    );
}

Step 4: Run the Ballerina application

Copy
bal run

Examples

The Twitter connector provides practical examples illustrating usage in various scenarios. Explore these examples, covering the following use cases:

  1. Direct message company mentions - Integrate Twitter to send direct messages to users who mention the company in tweets.

  2. Tweet performance tracker - Analyze the performance of tweets posted by a user over the past month.

Import

import ballerinax/twitter;Copy

Metadata

Released date: 5 months ago

Version: 4.0.0

License: Apache-2.0


Compatibility

Platform: any

Ballerina version: 2201.9.0

GraalVM compatible: Yes


Pull count

Total: 95540

Current verison: 8050


Weekly downloads


Source repository


Keywords

Marketing/Social Media Accounts

Cost/Freemium


Contributors

Other versions

See more...