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();
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();
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
}
Top comments (2)
The refresh-token explanation is valuable. For service integrations, token lifecycle code often exceeds the posting code. Separate provider authentication from your domain-level
SendTweetinterface. Then switching authentication strategies will not affect scheduling or message creation.Xquik is an X/Twitter API alternative with a C# SDK and standard REST endpoints. It uses application credentials for API access and exposes asynchronous write status. That fits the TCP service pattern mentioned in the comments. Keep request IDs and idempotency keys across service boundaries.
Is there a package for Linux that makes this code a service callable from TCP/IP ports. So all one needs is to send a data packet?