Quantcast
Channel: Tweetinvi a friendly Twitter C# library
Viewing all articles
Browse latest Browse all 4126

Updated Wiki: Documentation

$
0
0

Quick Start

Tweetinvi is a C# .NET API developped to simplify the life of developers will to access the Twitter API. It provides an easy access to the Twitter REST API and the Twitter stream API.

STARTCODECONFIGUREGO FURTHER

START

Before you start

Please verify that the time of your machine is correctly setup (both the time and the region).
Having an incorrect Time can result in receiving the 401 exception.

Understand Tweetinvi

Tweetinvi has been designed to be simple to use. Once you have setup your credentials, you can use all the methods available in the library.

Tweetinvi provides 2 ways to interact with the Twitter API.
  • Use a Tweetinvi.* static object to create, read, update or delete an object from Twitter.
  • Use a specific object's method in order to read or update information as well as deleting the object itself

Example to update a Tweet

// Using Static Tweet class to publish a Tweetvar tweet = Tweet.PublishTweet("hello");

// Using Static in 2 timesvar tweet = Tweet.CreateTweet("Hello");
Tweet.PublishTweet(tweet);

// Using objectvar tweet = Tweet.CreateTweet("Hello");
tweet.Publish();

Here is the list of the most used static classes you can use : Tweet, User, Timeline, Message, Search, Stream, TwitterCredentials, CredentialsCreator, ExceptionHandler, TweetinviConfig.

Here is the other static classes : RateLimit, TwitterAccessor, Trends, TweetList, SavedSearch, Geo, Help, Sync, TweetinviEvents, TweetinviContainer.

Credentials

Before using any method of the application you will need to specify your credentials.
The credentials system has been designed to be very simple. You only need to setup your credentials once in your application lifetime.

// Setup your credentials
TwitterCredentials.SetCredentials("Access_Token", "Access_Token_Secret", "Consumer_Key", "Consumer_Secret");

The credentials have a thread scope, it means that when modifying the credentials in a Thread, it will not affect the other threads. You can use the ApplicationCredentials to change the default credentials of all threads.

// Setup your application credentials
TwitterCredentials.SetCredentials("Access_Token", "Access_Token_Secret", "Consumer_Key", "Consumer_Secret");

You can also run a set of operations from a specific set of credentials

var credentials = TwitterCredentials.CreateCredentials("Access_Token", "Access_Token_Secret", "Consumer_Key", "Consumer_Secret");
TwitterCredentials.ExecuteOperationWithCredentials(credentials, () =>
{
        Tweet.PublishTweet("myTweet");
});

CODE

Timeline

// Simple requestvar homeTimelineTweets = Timeline.GetHomeTimeline();
var userTimelineTweets = Timeline.GetUserTimeline("userScreenName");

// Create a parameter for queries with specific parametersvar timelineParameter = Timeline.CreateHomeTimelineRequestParameter();
timelineParameter.ExcludeReplies = true;
timelineParameter.TrimUser = true;
var tweets = Timeline.GetHomeTimeline(timelineParameter);

User

// Get currently logged user - A logged user has unique features notably the ability to update its account settingsvar user = User.GetLoggedUser();

// Get a user from id/namevar user = User.GetUserFromId(USER_ID);
var user = User.GetUserFromScreenName([USER_SCREEN_NAME]);

// Get Friendsvar user = User.GetUserFromId(USER_ID);
var friends = user.GetFriends();

Tweet

// Publish simple tweetvar tweet = Tweet.PublishTweet("Hello!");

// Publish with mediabyte[] file = File.ReadAllBytes(filePath);
var tweet = Tweet.CreateTweetWithMedia("I love tweetinvi", file);
var imageURL = tweet.Entities.Medias.First().MediaURL;

// Publish with geo informationvar tweet = Tweet.CreateTweet("Hello guys");
tweet.PublishWithGeo(-54.73, -64.2);

// Retweet
tweet.PublishRetweet();

// Publish in to reply to a tweetvar myReplyTweet = Tweet.CreateTweet("Here is my reply!");
var replyTweet= Tweet.PublishTweetInReplyToTweet(myReplyTweet, tweet);

Message

// Publish a private message to a friend of yoursvar message = Message.PublishMessage("plop", [USER_ID]);

// Get Latest Messages Receivedvar latestMessagesReceived = Message.GetLatestMessagesReceived();

// Advanced var latestMessagesReceivedParameter = Message.GenerateGetLatestsReceivedRequestParameter();
latestMessagesReceivedParameter.SinceId = 10029230923;
var latestMessagesReceived = Message.GetLatestMessagesReceived(latestMessagesReceivedParameter);

Search

// Search the tweets containing tweetinvivar tweets = Search.SearchTweets("tweetinvi");

// Complex searchvar searchParameter = Search.GenerateSearchTweetParameter("tweetinvi");
searchParameter.SetGeoCode(-122.398720, 37.781157, 1, DistanceMeasure.Miles);
searchParameter.Lang = Language.English;
searchParameter.SearchType = SearchResultType.Popular;
searchParameter.MaximumNumberOfResults = 100;
searchParameter.Until = new DateTime(2013, 12, 1);
searchParameter.SinceId = 399616835892781056;
searchParameter.MaxId = 405001488843284480;
var tweets = Search.SearchTweets(searchParameter);

Rate Limits

RateLimit is a very complex part of the Twitter API because it is not complete and the documentation is very poor and out of date.
To simplify your life Tweetinvi implements a RateLimit handler. This RateLimit handler will in the measure of possible await for the RateLimits to be available before performing a query.

// Access you rate limitsvar rateLimits = RateLimit.GetCurrentCredentialsRateLimits();
Console.WriteLine("You can access your timeline {0} times.", rateLimits.StatusesHomeTimelineLimit.Remaining);

// Enable Tweetinvi RateLimit Handler
RateLimit.UseRateLimitAwaiter = true;

// Getting notified when your application is being stopped to wait for RateLimits to be available
RateLimit.QueryAwaitingForRateLimit += (sender, args) =>
{
    Console.WriteLine("{0} is awaiting {1}ms for RateLimit to be available", args.Query, args.ResetInMilliseconds);
};

You can also await manually for the RateLimits to be available.
TweetinviEvents.QueryBeforeExecute += (sender, args) =>
{
    var queryRateLimit = RateLimit.GetQueryRateLimit(args.Query);
    RateLimit.AwaitForQueryRateLimit(queryRateLimit);
};

Here are some methods that you might want to use.
// Get the RateLimit associated with a query, this can return nullvar queryRateLimit = RateLimit.GetQueryRateLimit("https://api.twitter.com/1.1/application/rate_limit_status.json");

// Pause the current thread until the specific RateLimit can be used
RateLimit.AwaitForQueryRateLimit(queryRateLimit);

// This stop the execution of the current thread until the RateLimits are available 
RateLimit.AwaitForQueryRateLimit("https://api.twitter.com/1.1/application/rate_limit_status.json");

// Tweetinvi uses a cache mechanism to store credentials RateLimits, this operation allows you to clear it.// If the UseRateLimitAwaiter option is enabled this will result in the RateLimits to be retrieved before the next query.
RateLimit.ClearRateLimitCache();

Streams

// Know everything that happens on an account - Check all the available events from Intellisense!var userStream = Stream.CreateUserStream();
userStream.TweetCreatedByMe += (s, a) => { Console.WriteLine("I posted {0}", a.Tweet.Text); };
userStream.TweetCreatedByFriend += (s, a) => { Console.WriteLine("{0} posted {1}", a.Tweet.Creator.Name, a.Tweet.Text); };
userStream.MessageReceived += (s, a) => { Console.WriteLine("You received the message : {0}", a.Message.Text); };
userStream.StartStream();

// Access the sample streamvar sampleStream = Stream.CreateSampleStream();
sampleStream.TweetReceived += (sender, args) => { Console.WriteLine(args.Tweet.Text); };
sampleStream.StartStream();

// Access the filtered streamvar filteredStream = Stream.CreateFilteredStream();
filteredStream.AddTrack("ladygaga");
filteredStream.MatchingTweetReceived += (sender, args) => { Console.WriteLine(args.Tweet.Text); };
filteredStream.StartStreamMatchingAllConditions();

CONFIGURE

Proxy

// Configure proxy without credentials
TweetinviConfig.CURRENT_PROXY_URL = "http://228.23.13.21:4287";

// Configure a proxy with Proxy with username and password
TweetinviConfig.CURRENT_PROXY_URL = "http://username:password@228.23.13.21:4287";

GO FURTHER

Request user Credentials

Tweetinvi allows developers to request credentials from user using the PIN or CallbackURL authentication systems.

Application and Captcha

// This method shows you how to create Application credentials. // This type of credentials do not take a AccessKey or AccessSecret.private ITemporaryCredentials CreateApplicationCredentials(string consumerKey, string consumerSecret)
{
    return CredentialsCreator.GenerateApplicationCredentials(consumerKey, consumerSecret);
}

// We need the user to go on the Twitter Website to authorize our applicationprivatevoid GoToTwitterCaptchaPage(ITemporaryCredentials applicationCredentials)
{
    var url = CredentialsCreator.GetAuthorizationURL(applicationCredentials);
    Console.WriteLine("Please go on {0}, to accept the application and get the captcha.", url);
}

// On the Twitter website the user will get a captcha that he will need to enter in the applicationprivatevoid GenerateCredentialsAndLogin(string captcha, ITemporaryCredentials applicationCredentials)
{
    var newCredentials = CredentialsCreator.GetCredentialsFromVerifierCode(captcha, applicationCredentials);
    
    // And now the user is logged in!
    TwitterCredentials.SetCredentials(newCredentials);
    
    var loggedUser = User.GetLoggedUser();
    Console.WriteLine("You are logged as {0}", loggedUser.ScreenName);
}

Website and URL callback

Please note that http://localhost:xxxx is not a valid redirection URL for the twitter authentication platform!

var applicationCredentials = CredentialsCreator.GenerateApplicationCredentials(consumerKey, consumerSecret);
var url = CredentialsCreator.GetAuthorizationURLForCallback(applicationCredentials, "https://tweetinvi.codeplex.com");
Console.WriteLine("Go on : {0}", url);
Console.WriteLine("When redirected to your website copy and paste the URL: ");
            
// Enter a value like: https://tweeetinvi.codeplex.com?oauth_token={tokenValue}&oauth_verifier={verifierValue}var callbackURL = Console.ReadLine();

// Here we provide the entire URL where the user has been redirectedvar newCredentials = CredentialsCreator.GetCredentialsFromCallbackURL(callbackURL, applicationCredentials);
Console.WriteLine("Access Token = {0}", newCredentials.AccessToken);
Console.WriteLine("Access Token Secret = {0}", newCredentials.AccessTokenSecret);

return newCredentials;

Exceptions

To simplify your development and not needing to put try/catch around each of the operation twitter operates, Tweetinvi contains an ExceptionHandler. When an exception occurs, it will retrieve and format all the information for you. Tweetinvi will not raise any exception but the response will be defaulted (e.g. getting a user who does not exist will return null).

var exceptionStatusCode = ExceptionHandler.GetLastException().StatusCode;
var exceptionDescription = ExceptionHandler.GetLastException().TwitterDescription;
var exceptionDetails = ExceptionHandler.GetLastException().TwitterExceptionInfos.First().Message;

Custom queries and Twitter Accessor

Tweetinvi does not yet implement all the features provided by the Twitter API. If a feature is not yet implemented please use the Twitter Accessor to get the information back from an URL.

// Get a tweet from the Twitter Accessorvar tweetDTO = TwitterAccessor.ExecuteGETQuery<ITweetDTO>("https://api.twitter.com/1.1/statuses/show.json?id=210462857140252672");
var tweet = Tweet.GenerateTweetFromDTO(tweetDTO);

Please not that you must use the DTO classes/interfaces as target of the ExecuteQuery method. You can then transform it with the CLASS.GenerateCLASSFromDTO of your target type.

Windows RT, Windows Phone 8 and Async

Tweetinvi 0.9.1.0 introduced the capability to develop applications targeting Windows Phone and Windows RT with the implementation of the Async-Await pattern.

All the static classes performing a webrequest have their 'async' equivalent.

// Classic invokevar user = User.GetLoggedUser(); 

// Async invokevar user = await UserAsync.GetLoggedUser();

All the instance methods performing a webrequest also have their 'async' equivalent.
var user = User.GetLoggedUser();

// Get timeline synchronouslyvar timeline = user.GetUserTimeline();

// Get timeline asyncrhonouslyvar timeline = await user.GetUserTimelineAsync();

Get Json with Tweetinvi

Tweetinvi allow developers to access the json from queries. To do so just use the Json classes like the others. Please not that not all the features are yet provided in the Json classes, if I will be happy to implement them for your on a simple request in a discussion.

// Get object resultvar result = Search.SearchTweets("tweetinvi");

// Get json resultvar jsonResult = SearchJson.SearchTweets("tweetinvi");

Viewing all articles
Browse latest Browse all 4126

Trending Articles