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.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 provide 2 ways to interacting 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
// 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
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.ApplicationCredentials = TwitterCredentials.CreateCredentials("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"); });
Timeline
// Simple requestvar tweets = Timeline.GetHomeTimeline(); // 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]);
User Feed
// 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();
Request user Credentials
Tweetinvi allows developers to request credentials from user using the PIN or CallbackURL authentication systems.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;
Rate Limits
// Access you rate limitsvar rateLimits = RateLimit.GetCurrentCredentialsRateLimits(); Console.WriteLine("You can access your timeline {0} times.", rateLimits.StatusesHomeTimelineLimit.Remaining);
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);
Stream
// 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();
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.
Json
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");
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();