DEV Community

Frederik Van Lierde
Frederik Van Lierde

Posted on

How to Post a Tweet with Twitter API V2

The following posts shows an easy way to automate Tweets using the latest Twitter API V2

The OAUTH Access token received from Twitter is only valid for 2 hours. The code will autoatically refreh the token.

You need offline.access to your scopes, this way you will get a refresh token

The NuGet Packages will developped step by step, giving you more features.
  

Prerequisites

  

Get Access & Refresh Token

  • Scopes: tweet.read%20tweet.write%20users.read%20offline.access
  • Create a Web Page, and add the link to your App OAUTH Settings (This can be a localhost)
  • CodeVerifier is an unique text, and should be saved temp., as in the next step, you will need it again. This parameter is required for Twitter OAUTH2
TwitterHelper _twitter = new()
            {
                ClientId = "CLIENT APP ID";
                ClientSecret = "CLIENT APP SECRET",
                RedirectUri = "YOUR PAGE URL TO REDIRECT",
                Scope = "TWITTER SCOPES,
                CodeVerifier = "Dhk87jJsks234"
            };
ViewBag.TwitterOAuthRequestUrl = _twitter.GetOAuthTokenUrl();
Enter fullscreen mode Exit fullscreen mode

ViewBag.TwitterOAuthRequestUrl is the link the user should click on.

  

When the user accept your scopes and is redirected to your webpage

TwitterHelper _twitter = new()
            {
                ClientId = "CLIENT APP ID";
                ClientSecret = "CLIENT APP SECRET",                
                CodeVerifier = "Dhk87jJsks234",
                UseUrlEncodedHeader = true,
                OAuthCode = code,
            };
await _twitter.GetAccessToken();
Enter fullscreen mode Exit fullscreen mode

The access code, refresh code, expiry dates are now accessible via _twitter object and you can save them in a database, or appsettings file
  

Send a Tweet

async Task SendTweet()
{
    // Load the Access & Refresh Token, Access Expiry Date

    TwitterHelper _twitter = new("CLIENT APP ID",
                                 "CLIENT APP SECRET",
                                 "ACCESS TOKEN",
                                 "ACCESS TOKEN EXPIRY DATE",
                                 "REFRESHTOKEN"
    );

    var _tweetID = await _twitter.Tweet("Hello Twitter! via CodeHelper.API.Twitter.V2");

    // when changed: save your Access & Refresh Token, Access 
    // Expiry Date
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)