Git Product home page Git Product logo

tweetmoasharp's Introduction

This is a fork of TweetSharp, the fine work of Daniel Crenna. v2.3.1 was the final release of TweetSharp, this builds on that.

This repository includes the latest code from the TweetSharp repository (which is newer than the published TweetSharp nuget package) and includes support for long twitter id's. Addtionally there are WinRT compatible libraries with basic async/await support.

Build status

NuGet Badge

Async Auth Examples

A number of people struggle with using TweetMoaSharp on platforms such as Windows Phone, WinRT and UWP because these platforms do NOT suppport "synchronous calls". Any call that involves I/O much be made "asynchronously" so it doesn't block the UI thread. Since most TweetMoaSharp methods access the network, you must use the async versions of those methods on these platforms.

The original TweetSharp samples are all synchronous method based (although me async patterns were supported). People tend to try these samples on the platforms where synchronous methods aren't supported. Below are two async samples to help get you started on these platforms.

Task Based Async

This is recommended on platforms that support it (WinRT/UWP/.Net 4.5+).

using TweetSharp;
using System.Threading.Tasks;

// Note: This method containing this code must be marked 'async'

// Pass your credentials to the service
TwitterService service = new TwitterService("consumerKey", "consumerSecret");

// Step 1 - Retrieve an OAuth Request Token
OAuthRequestToken requestToken = await service.GetRequestTokenAsyc();

// Step 2 - Redirect to the OAuth Authorization URL
Uri uri = service.GetAuthorizationUri(requestToken);
Process.Start(uri.ToString());

// Step 3 - Exchange the Request Token for an Access Token
string verifier = "123456"; // <-- This is input into your application by your user
OAuthAccessToken access = await service.GetAccessTokenAsync(requestToken, verifier);

// Step 4 - User authenticates using the Access Token
service.AuthenticateWith(access.Token, access.TokenSecret);
var result = await service.ListTweetsMentioningMeAsync();
IEnumerable<TwitterStatus> mentions = result.Value;
Callback Based Async

This is available on older platforms, like Windows Phone (pre WinRT).

using TweetSharp;

TweetSharp.TwitterService ts = new TweetSharp.TwitterService("MyConsumerKey", "MyConsumerSecret");
//Step 1, get a request token
ts.GetRequestToken((token, response) =>
{
	//If we got an ok response
	if (response.StatusCode == System.Net.HttpStatusCode.OK)
	{
		//Step 2 - Convert to an auth uri
		var authUri = ts.GetAuthorizationUri(token);

		//Display the page at the auth uri location to the user
		//Probably use the web application broken, or your own web view

		// Step 3 - Exchange the Request Token for an Access Token
		string verifier = "123456"; // <-- This is input into your application by your user
		ts.GetAccessToken(token, verifier, (accessToken, atResponse) =>
		{
			// Step 4 - Provide the auth token to the TwitterService and then make an
			// authed call.
			ts.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
			ts.ListTweetsMentioningMe(new TweetSharp.ListTweetsMentioningMeOptions(), (statuses, sResponse) =>
			{
				// The variables "statues" contains the returned list of tweets.
			});
		});
	}
});

The following is from the (latest version of the) original TweetSharp readme

Addressing issues with deserialization

In some cases, and mostly reported when trying to access the timeline of a protected user, the deserializer can get into an infinite recursion state that causes a StackOverflowException. The ability to reproduce this comes and goes, as it's mainly due to some brittleness in the serializer caused by trying to anticipate too many possible branches of code. Currently this use case seems to work. Twitter's JSON structures are not typical class-with-properties mappings meaning they need custom conversion. After several years, this code looks long in the tooth and probably will run into similar issues now or in the future. You can override the serializer by either setting the TwitterService.Deserialize property instantiation or using the constructor overload, if you have the appetite to replace it with something better. - Daniel

Introduction

TweetSharp is a Twitter API library that greatly simplifies the task of adding Twitter to your desktop, web, and mobile applications. You can build simple widgets, or complex application suites using TweetSharp. The second version, a rewrite, was designed to be lighter, faster, and more intuitive than the original. You write fewer lines of code, make fewer decisions, and get better results. Visual Studio T4 templates are employed to automatically generate new API methods from a simple text-based DSL.

Open source support

This project is open source software. I am happy to accept any reasonable pull requests, and the code is written with Visual Studio T4 templates, making it ridiculously easy to extend for any API methods that Twitter introduces in the future. Historically, almost no pull requests are received, so please plan accordingly, engage commercial support, or help out!

Commercial support

I no longer offer commercial support services for TweetSharp. It is now in its final state. TweetSharp V2 in general wouldn't have been possible without the sponsorship of SmartParents.

SmartParents

Learn the Twitter API

Make sure you visit (http://dev.twitter.com) to get acquainted with the Twitter API. Most of the time, confusion around the methods in this library are a result of not understanding Twitter's requirements, or the OAuth authentication workflow.

Hello, Twitter

using TweetSharp;

// In v1.1, all API calls require authentication
var service = new TwitterService(_consumerKey, _consumerSecret);
service.AuthenticateWith(_accessToken, _accessTokenSecret);

var tweets = service.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions());
foreach (var tweet in tweets)
{
    Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);
}

OAuth Authentication

The first step to accessing the Twitter API is to create an application at (http://dev.twitter.com). When that process is complete, your application is issued a Consumer Key and Consumer Secret. These tokens are responsible for identifying your application when it is in use by your customers. Once you have these values, you can create a new service and pass them in.

Authenticating a client application (i.e. desktop)

using TweetSharp;

// Pass your credentials to the service
TwitterService service = new TwitterService("consumerKey", "consumerSecret");

// Step 1 - Retrieve an OAuth Request Token
OAuthRequestToken requestToken = service.GetRequestToken();

// Step 2 - Redirect to the OAuth Authorization URL
Uri uri = service.GetAuthorizationUri(requestToken);
Process.Start(uri.ToString());

// Step 3 - Exchange the Request Token for an Access Token
string verifier = "123456"; // <-- This is input into your application by your user
OAuthAccessToken access = service.GetAccessToken(requestToken, verifier);

// Step 4 - User authenticates using the Access Token
service.AuthenticateWith(access.Token, access.TokenSecret);
IEnumerable<TwitterStatus> mentions = service.ListTweetsMentioningMe();

Authenticating a browser application

using TweetSharp;

public ActionResult Authorize()
{
    // Step 1 - Retrieve an OAuth Request Token
    TwitterService service = new TwitterService("consumerKey", "consumerSecret");
    
    // This is the registered callback URL
    OAuthRequestToken requestToken = service.GetRequestToken("http://localhost:9090/AuthorizeCallback"); 
    
    // Step 2 - Redirect to the OAuth Authorization URL
    Uri uri = service.GetAuthorizationUri(requestToken);
    return new RedirectResult(uri.ToString(), false /*permanent*/);
}

// This URL is registered as the application's callback at http://dev.twitter.com
public ActionResult AuthorizeCallback(string oauth_token, string oauth_verifier)
{
    var requestToken = new OAuthRequestToken {Token = oauth_token};
    
    // Step 3 - Exchange the Request Token for an Access Token
    TwitterService service = new TwitterService(_consumerKey, _consumerSecret);
    OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier);

    // Step 4 - User authenticates using the Access Token
    service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
    TwitterUser user = service.VerifyCredentials();
    ViewModel.Message = string.Format("Your username is {0}", user.ScreenName);
    return View();
}

xAuth Authentication

If you are building a mobile application and want to benefit from a seamless authentication experience with no additional steps for the user, you need to enroll your application in Twitter's xAuth support. You must complete this step in order for xAuth to function correctly.

using TweetSharp;

// OAuth Access Token Exchange
TwitterService service = new TwitterService("consumerKey", "consumerSecret");
OAuthAccessToken access = service.GetAccessTokenWithXAuth("username", "password");

OAuth Delegation with Echo

Twitter provides OAuth Echo support, which allows you to use other services like TwitPic by delegating the user's existing credentials. TweetSharp uses Hammock both internally and as a tool for you to make delegated requests. This example shows how you would use TweetSharp and Hammock together to post an image on TwitPic using OAuth. You could use any HTTP client as long as you add the same request meta-data.

using TweetSharp;
using Hammock;

TwitterService service = new TwitterService(consumerKey, consumerSecret);
service.AuthenticateWith("accessToken", "accessTokenSecret");

// Prepare an OAuth Echo request to TwitPic
RestRequest request = service.PrepareEchoRequest(); 
request.Path = "uploadAndPost.xml";
request.AddFile("media", "failwhale", "failwhale.jpg", "image/jpeg");
request.AddField("key", "apiKey"); // <-- Sign up with TwitPic to get an API key
request.AddField("message", "Failwhale!");

// Post photo to TwitPic with Hammock
RestClient client = new RestClient { Authority = "http://api.twitpic.com/", VersionPath = "2"};
RestResponse response = client.Request(request);

Discovering API Methods

TweetSharp uses a consistent method naming convention to help you locate the method you're looking for. In general, methods that return multiple results begin with List, while methods that return a single result begin with Get. Most methods, like the Twitter API, have additional parameters for obtaining pages of results rather than the default count. Keep in mind that paging methods have limits that you can confirm at (http://dev.twitter.com). Here's a sample of some of the most common Twitter API methods:

using TweetSharp;

TwitterStatus GetTweet(new GetTweetOptions { Id = 12345 });
TwitterStatus SendTweet(new SendTweetOptions { Status = "Hello, world!" });

IEnumerable<TwitterStatus> ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { SinceId = 12345 ));
IEnumerable<TwitterStatus> ListTweetsMentioningMe(new ListTweetsMentioningMe { SinceId = 12345 ));

Dealing with Twitter API Rate Limiting

Twitter limits the frequency of all API calls in a variety of ways, to help ensure the service is not abused. This means that your applications will have to account for possible rate limit shortages at the user and API endpoint level. Client applications that are meant for public consumption usually use the rate limit profile of users that are logging in to their application. You can find out more about rate limiting at (https://dev.twitter.com/docs/rate-limiting/1.1).

TweetSharp provides two ways to access rate limiting data. You can either make an explicit API call to retrieve it, or inspect the TwitterResponse's RateLimitStatus property, if it's available. The latter option conserves HTTP traffic, as the information is embedded in the HTTP response itself.

using TweetSharp;

TwitterService service = new TwitterService("consumerKey", "consumerSecret");
service.AuthenticateWith("accessToken", "accessTokenSecret");

// Option 1 - Retrieve from the API (a list of all endpoints and rates)
TwitterRateLimitStatusSummary rate = service.GetRateLimitStatus();

// Option 2 - Retrieve from the response (scoped to the last request)
IEnumerable<TwitterStatus> mentions = service.ListTweetssMentioningMe(new ListTweetsMentioningMeOptions());
TwitterRateLimitStatus rate = service.Response.RateLimitStatus;
Console.WriteLine("You have used " + rate.RemainingHits + " out of your " + rate.HourlyLimit);

Asynchronous Methods

TweetSharp supports executing methods asynchronously, and provides two styles of operation. The first is a delegate style, where you pass an Action into the named method after any optional parameters. This Action provides you with both the expected response that you would get if you called the method sequentially, as well as the response info you would have accessed on TwitterService's Response property.

Asynchronous operation (delegate style)

using TweetSharp;

TwitterService service = GetAuthenticatedService();
IAsyncResult result = service.ListTweetsOnHomeTimeline(
    (tweets, response) =>
        {
            if(response.StatusCode == HttpStatusCode.OK)
            {
                foreach (var tweet in tweets)
                {
                    Console.WriteLine("{0} said '{1}'", tweet.User.ScreenName, tweet.Text);
                }
            }
        });

In addition to delegate-based asynchronous methods, TweetSharp lets you simplify asynchronous operations with the familiar .NET Begin/End pattern. This style of operation involves calling the same methods as the synchronous style, but prefixing the method with Begin. Similarly, to retrieve the results you were looking for, you call the appropriate method beginning with End, with the option to provide a timeout value.

Asynchronous operation (begin/end style)

using TweetSharp;

var service = GetAuthenticatedService();
IAsyncResult result = service.BeginListTweetsOnHomeTimeline(new BeginListTweetsOnHomeTimelineOptions());
IEnumerable<TwitterStatus> tweets = service.EndListTweetsOnHomeTimeline(result);

foreach (var tweet in tweets)
{
    Console.WriteLine("{0} said '{1}'", tweet.User.ScreenName, tweet.Text);
}

Using Windows Phone

TweetSharp is designed with Windows Phone 7 in mind. Each sequential method on TwitterService also has an asynchronous equivalent for Windows Phone. Rather than expect a response, each method asks for a delegation Action to perform, which provides the expected result, as well as a wrapper class to help you handle unexpected results in your application.

using TweetSharp;

Dispatcher dispatcher = Deployment.Current.Dispatcher;
TwitterService service = new TwitterService("consumerKey", "consumerSecret");
service.AuthenticateWith("accessToken", "accessTokenSecret");

// Example: Getting Mentions
service.ListTweetsMentioningMe(new ListTweetsMentioningMeOptions(), (statuses, response) =>
{
    if(response.StatusCode == HttpStatusCode.OK)
    {
        foreach (var status in statuses)
        {
            TwitterStatus tweet = status;
            dispatcher.BeginInvoke(() => tweets.Items.Add(tweet));
        }
    }
    else
    {
        throw new Exception(response.StatusCode.ToString());
    }
});

// Example: Posting a Tweet
service.SendTweet(new SendTweetOptions { Status = "Tweeting with #tweetsharp for #wp7"}, (tweet, response) =>
{
    if (response.StatusCode == HttpStatusCode.OK)
    {
        dispatcher.BeginInvoke(() => tweets.Items.Add(tweet));
    }
    else
    {
        throw new Exception(response.StatusCode.ToString());
    }
});

Data Format Handling

By default, TweetSharp handles serialization and deserialization details for you. Twitter v1.1 only supports JSON serialization. the RawSource property on each model contains the JSON retrieved from Twitter for each object.

If you go one step further and decide you don't trust our serializer, you can change TwitterService's Serializer and Deserializer properties, setting them to Hammock-compatible interfaces, and TwitterService will then defer to your custom serializer in all requests.

using TweetSharp;
using Hammock.Serialization;

MyAwesomeSerializer serializer = new MyAwesomeSerializer();
TwitterService service = new TwitterService("consumerKey", "consumerSecret");
service.Serializer = serializer;
service.Deserializer = serializer;

Handling Errors

There are three ways of handling errors at the Twitter API level.

  • You can use the TwitterResponse object to inspect details about the request and act accordingly. This object is available sequentially using TwitterService's Response property, which means the Response property will update after each API call is complete. If you're using Windows Phone 7, you get the TwitterResponse object passed into each Action delegate, so you know the response you're accessing belongs to the request that's returning through the callback.

  • TweetSharp uses a relaxed JSON parsing strategy to mitigate exceptions when API objects change. TweetSharp will return a null value if something went wrong, and the Response object's TwitterError property will be populated with more details.

  • If you're not confident with the deserialization of your object, you can use the RawSource property that exists on all Twitter model objects to inspect the actual JSON response that was returned by Twitter, specific to that object. This means if you returned a collection of tweets, each tweet's RawSource will contain the JSON for that specific tweet. This is helpful if you want to perform custom parsing or tracing of the raw data.

Error Handling Examples (sequential service calls)

using TweetSharp;

TwitterService service = new TwitterService(_consumerKey, _consumerSecret)();

// Missing authentication; this call will fail
IEnumerable<TwitterStatus> mentions = service.ListTweetsMentioningMe(new ListTweetsMentioningMeOptinos()); 

// Look for bad requests by inspecting the response for important info
if(service.Response.StatusCode == HttpStatusCode.OK) // <-- Should be 401 - Unauthorized
{ 
    // Look for a null object if a real error, or serialization problem, occurred
    if(mentions == null)
    {
        // If a real error occurred, you can get it here        
        TwitterError error = service.Response.TwitterError;
        if(error != null)
        {
            // You now know you have a real error from Twitter, and can handle it
        }
        else
        {
            // It could be an issue with serialization, you can check the content
            var content = service.Response.Response;
            
            Console.WriteLine(content);
            
            // And try to deserialize it into something else
            var myError = service.Deserialize<MyTwitterError>(content);
        }
    }
}
else
{
    // Likely this is an error; we don't have to go fishing for it
    TwitterError error = service.Response.TwitterError;
    if(error != null)
    {
        // You now know you have a real error from Twitter, and can handle it
    }
}

Using Twitter Entities

TweetSharp supports Twitter's entities feature. This feature provides additional metadata for locating mentions, links, and hashtags embedded in tweet text. TweetSharp goes a step further, emulating the entities support for classes that Twitter currently doesn't support, that implement ITweetable; namely TwitterStatus, TwitterDirectMessage and TwitterSearchStatus. All three of these classes contain an Entities property. This allows you to find these elements in UI columns that contain multiple tweet types, via the ITweetable interface. To retrieve all of the entities in an ITweetable ordered by where they appear in the text itself, you can call the Coalesce method on the relevant TwitterEntities instance.

Client Development Features

TweetSharp is a bit more than an API wrapper, it also provides support for client application development beyond the data. In this section, TweetSharp's features specific to developing client applications on the .NET Framework are highlighted.

  • All model objects are [Serializable], implement IPropertyNotifyChanged, use virtual signatures, and implement DataContract / DataMember where supported. This means all of our model objects are persistable in frameworks like NHibernate, observable in WPF, and serializable for over-the-wire communication in WCF.

  • ITweetable and ITweeter: TwitterStatus, TwitterDirectMessage, and TwitterSearchStatus all implement ITweetable, which is an interface to make it easier to blend tweets from different sources into the same UI display. ITweeter helps encapsulate common user display properties, and TweetSharp even provides emulation of the entity metadata for non-timeline ITweetables; this means that you can access mentions, hashtags, and links embedded in the text of any ITweetable, in the order they appear.

These are the UI interfaces:

public interface ITweetable
{
    long Id { get; }
    string Text { get; }
    ITweeter Author { get; }
    DateTime CreatedDate { get; }
    TwitterEntities Entities { get; }
}

public interface ITweeter
{
    string ScreenName { get; }
    string ProfileImageUrl { get; }
}

tweetmoasharp's People

Contributors

adrianpell avatar ajukraine avatar arnoldchan avatar bhasden avatar braahyan avatar calbucci avatar caraxe avatar collinsauve avatar danielcrenna avatar dansaltmer avatar davidchristiansen avatar diaconu13 avatar djhi avatar juliengrimault avatar karlisf avatar kensykora avatar mfloryan avatar mikeosborn avatar nyxtom avatar rheckart avatar samkelleher avatar simcon avatar timurgilfanov avatar yortw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tweetmoasharp's Issues

How can i undo self retweet?

there is unretweet in official API but not in moasharp. I'm using delete api to undo retweet but it is not good for undo self retweet. Is it not added yet or not supported?

Adding TweetMoaSharp via NuGet adds also a reference to NUnit

Hi community,

I was just wondering, why adding TweetMoaSharp to my C# project via NuGet also adds a reference to NUnit? Is this really necessary? I prefer to have production code and related unit tests in two different projects, so you can easily publish production code as NuGet package without a reference to unit test libraries.

Best Regards,
Mark

Upload media not working

I cannot upload media and attach the mediaId with a tweet. It always return null for the uploadmedia method.

Any plans for application-only authorization?

The ability to pull down a public timeline would be a welcome addition... and would solve a big problem for me particularly. I really only need it for GET statuses/user_timeline...

Posting Image along with summary and URL

Hi,
I'm using TweetResharp to post an article on subscribed Twitter account. I'm able to post the tweet header and just Image. But I need to be able to post something like what i have attached. please let me know if we have this provision with TweetSharp?

tw

get retweets media

hi
this is my code . i have no media entities for retweets . whats th problem . how can i fix it
var service = new TwitterService(_consumerKey, _consumerSecretKey); service.AuthenticateWith(_acessToken, _accessTokenSecret); //var currentTweets = service.ListTweetsOnSpecifiedUserTimeline(screenName: "screen name", page: 1, count: 100); var list = service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions() { ScreenName = "ali_persian999", });

Uploading A Video As Media Won't Work

Hi Yortw, thank you for the time in maintaining a really nice C#.net wrapper for C# developers.

I was trying to upload a video using service.UploadMedia(Options) where Options contained the stream of my video file. The function returned null. It works for Images but not for videos. Please advise.

If there's no video uploading api wrapper yet, then please consider this as a feature request.

Many thanks,

GetRequestToken on Windows Store App

I pulled down your package from NuGet for use in a windows store app. I tested it with my test console and everything works great. When I added the package to the windows store app I am getting an error indicating GetRequestToken() requires at least 1 parameter, which doesnt seem to be required in my test use of the package.

UploadMedia is not working with Mono and Linux (Docker Container)

At first, thank you, to bring tweetsharp back to live.
We use TweetMoaSharp and it works great with windows, but we switched our infrastructure to linux docker.
Now, we have a problem with UploadMedia.
Twitter gives us an error back.
The stream content object is not correct.
The problem is the hammcock library, it uses to create the stream content object an StringBuilder. This StringBuilder use Environment.Newline to add new lines.
This Newlines are different between Windows and Linux.

I know this is a small issue, we have our workaround and .NET CORE is the new way to go. But i thought it is not a bad idea to report this issue.

Can't Tweet with Some Characters

There is an issue in the original TweetSharp repository that suggests some characters cause tweets to fail. This is specifically listed as a problem when the tweet includes media, but may just be an issue with the character encoding regardless of what else in the tweet. A sample message that causes the problem is;

"Hello à ...."

There is also a suggestion that the apostrophe character ' may cause similar issues. To quote the original issue;

After search, I have immediately error if message contains ' (quote) character such as " L'image ". If I try the message " L image ", tweet will be send with no error.

Include Hammock as a dependency

How come you have choosen to include the Hammock.ClientProfile assembly in the package?
Wouldn't it make more sense to declare it a dependency?

TweetSharp vs Tweetmoasharp

Newbie using Twitter with those targets and questions:

Which latest API Twitter ?
Limitations for get tweets, download images, etc ?
How can I get your all tweets list ?
And download photos and videos from anyone timeline too ?
How get the list of followers and following ?
How send DM anyone user ?
How can I follow to user ?
How manage lists ?
How get favorites lists ?

I want to do it programmatically using C# but for .NET, I have not seen many samples official Twitter:
NOw, I have found 2 API: TweetSharp vs Tweetmoasharp
https://github.com/danielcrenna/tweetsharp
https://github.com/Yortw/tweetmoasharp/

Which is the recommended ? Can I do all my targets ?

Mindly notes:

Any good getting started with Tweetmoasharp? step by step in 10 minutes?

IMHO, better samples for minimize learning curve are real applications with full source code and good patterns and practices

Full source code sample REAL application? not Demo, only real applications?
Like for small to medium applications development, but open source, if you can sharing or maybe another real project or production-ready application using.

main influences, are full of innovative ideas that can free our minds to explore new techniques, patterns and paradigms.

You want to use technologies that allow for rapid development, constant iteration, maximal efficiency, speed, robustness and more. You want to be lean and you want to be agile. You want to use technologies that will help you succeed in the short and long term. And those technologies are not always easy to pick out.

Mindly notes 2

Why not working together ?

https://tweetinvi.codeplex.com/90
https://www.nuget.org/packages/TweetinviAPI45

https://linqtotwitter.codeplex.com/36
https://www.nuget.org/packages/linqtotwitter28

https://github.com/opentig/TwitterIrcGateway30

https://github.com/danielcrenna/tweetsharp
https://github.com/Yortw/tweetmoasharp/

How to use TwitterService.StreamFilter with options

Is it possible to specify any options with the filter. When I use this method the twitter endpoint is yelling at me: "No filter parameters found. Expect at least one parameter: follow track locations".

Problem with UAP?

Hi,

is there a problem with UAP again? If i create a NEW App. Download only tweetmoasharp with nuget go to the "MainPage.xaml.cs" und use this function. The App never comes the line with "returnval = ....". So it looks like SearchAsync got a problem :/.

public static async Task<List<TwitterStatus>> GetTestTweets()
{
    var returnval = new List<TwitterStatus>();

    try
    {
        var service = new TwitterService(ConsumerKey, ConsumerSecret);
        service.AuthenticateWith(AccessToken, AccessTokenSecret);

        var results = await service.SearchAsync(new SearchOptions { Q = "#test", Count = 50 });
        returnval = new List<TwitterStatus>(results.Value.Statuses);
    }
    catch (Exception exc)
    {
        System.Diagnostics.Debug.WriteLine(exc.Message);
    }

    return returnval;
}

The same code works very well on a normal WPF or Command Line-Application.

URL Shortening -- not working?

Supposed to check help/configuration to know how many characters are available for shortening, I can't figure out how to access that via TweetSharp, so I'm estimating a few more than currently used.

However, when I pass the status with a longer URL, it should auto-shorten according to Twitter Dev, but I'm getting Error 186, too long.

Any advice for where to look?

Fetching 280 character tweets

Is any development being made in TweetMoaSharp to support fetching tweets longer than 140 characters ?(up to 280 characters, the current maximum)

TwitterService.ListMutedUsers Returns Id's not Users

There is already a ListMutedUserIds and ListMutedUsers should return user objects rather than ids to be consistent with the rest of the API. Although this would be a breaking change it seems worth while fixing.

ListDirectMessagesSent() does work ?

I've been trying for days to get the list of the direct messages that I have and it doesn't do anything,it works or is just deprecated ?

Thank you!

Access to other Twitter APIs - e.g. Ads API

I'm working on access to the Twitter Ads API - which lives on a different endpoint (https://ads-api.twitter.com). Unless I'm totally mistaken, that doesn't seem to fit into the current model where the endpoint is in Globals.

Do you have any suggestions on how to go about this and would you be interested in a PR for this when I'm done?

Great job on keeping this alive :-)

Profile Banner Url

users/lookup provide profile_banner_url field to access profile banner path.
Will you add this field to TwitterUser class?

Tweet with broken encoding causes issues with TextAsHtml and serializing as XML complains about

A bug in my application surfaced when pulling in this tweet: https://twitter.com/BZTHEEZE/status/637228279825608706 with Emoji and what looks like a complete gibberish character.

I'm not sure if there's anything that can be done about this I'll describe the symptoms and then say what I think the issue may be. My experience with Unicode encodings isn't good enough to be sure.

This issue also appears in Tweetsharp 2.3.1.2-unofficial

First, TextAsHtml ends with the link https://t.co/W2TeREt0Hdt0Hd - the extra t0Hd at the end shouldn't be there.

Finally, when I include this string in an object which gets serialized to XML (an RSS feed), it complains that a high surrogate character must always be paired with a low surrogate character.

I would imagine the slightly skewed link is because the offsets in the entities returned by Twitter don't match the reality. It appears that source of the Tweet itself is damaged, as if it's sending UTF-16 bytes over the wire and declaring them as UTF-8 or something.

Serializing to Json, including the string in a website or my own API all work fine, the issue for me only surfaces when I try to serialize in XML. Therefore before I serialize the object, I run the text through these functions:

private static readonly Encoding Utf8Encoder = Encoding.GetEncoding(
    "UTF-8",
    new EncoderReplacementFallback(string.Empty),
    new DecoderExceptionFallback());

private static string RepairStringEncoding(string str)
{
    return Utf8Encoder.GetString(Utf8Encoder.GetBytes(str));
}

...which serializes without exceptions albeit with the extra characters in the link (t0Hd).

Thanks for reading, I'm curious to know your thoughts and whether you think such an issue should be addressed within TweetMoaSharp itself or by the applications that use it. And whether you think the Tweet is "damaged" or perhaps a bug in their API?

Thanks as always,
Steve

Send Tweet with Multiple Images

I believe Twitter implemented this after TweetSharp stopped being supported, so it probably doesn't work. We should implement this feature.

Any change of a NET46 build?

All is working well, it's just that Visual Studio keeps complaining about conflicts between different versions of the same dependent assembly.

Incompatible with .Net Core 1.0

I'm putting together a test/example .NET Core app and am having issues using your library. When adding TweetMoaSharp from NuGet I get the following output from the Package Manager.

Package TweetMoaSharp 3.0.0.15 is not compatible with netcoreapp1.0 (.NETCoreApp,Version=v1.0). Package TweetMoaSharp 3.0.0.15 supports:
  - net20 (.NETFramework,Version=v2.0)
  - net35 (.NETFramework,Version=v3.5)
  - net40 (.NETFramework,Version=v4.0)
  - net45 (.NETFramework,Version=v4.5)
  - portable-win81+wpa81 (.NETPortable,Version=v0.0,Profile=Profile32)
  - sl4 (Silverlight,Version=v4.0)
  - sl4-wp (Silverlight,Version=v4.0,Profile=WindowsPhone)
  - sl4-wp71 (Silverlight,Version=v4.0,Profile=WindowsPhone71)
One or more packages are incompatible with .NETCoreApp,Version=v1.0.

Any suggestions on how to get the library working properly in .NET Core 1.0 or are there dependencies that make it impossible?

Problem with Hammock.WinRT.dll

Hi, I have noticed a problem with TweetMoaSharp nuget package. I have installed it from nuget repo, it's working fine, but when I created an appx package of my Windows Phone 8.1 project, it can't pass tests form Windows App Certification Kit. The is a problem with Hammock.WinRT.dll because it is build in debug mode rather than release mode. Can you provide my a release version of Hammock.WinRT.dll or change it in nuget package?
Kacper

Can't post to Twitter feed

I'm using the latest TweetMoaSharp and am a bit baffled with this error.

It is in a server environment, where the client sends us the accessToken and accessTokenSecret to be stored online. I'm running the following code:

var service = new TwitterService("consumerKey", "consumerKeySecret");
service.AuthenticateWith("accessToken", "accessTokenSecret");
var result = service.SendTweet(new SendTweetOptions { Status = "Test post" });

However at the end, result is null, and the post does not appear.

Support new direct_messages/events API

The old DM API is deprecated and the migration guide suggest that:

Developers should migrate to the relative API endpoint as described below by August 16th, 2018.

This is a very significant rewrite of the DM API. Main changes to be aware of:

  • Pagination is achieved via cursors rather than since_id and max_id
  • This combines both sent and received message
  • Only 30 days worth of events can be retreived
  • The response events no longer contain the screenname, only the user id. This makes it difficult to determine who is sending and who is receiving the message if consumer is used to working with screennames. (thread on the forum)

Additionally, based on the documentation provided, I can't tell what events.message_create.message_data.entities.symbols includes.

Incompatibility with Newtonsoft.json.dll 7

I've tried to use the 4.0 dll in a project where we have upgraded to 4.0 because a new dll requires Newtonsoft.json.dll with the latest 7.0 version.
Unfortunately that causes an error trying to use the released dll

System.IO.FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

I've managed to get the sources and compile just the project that I need with the updated dll, but I think that it would be great if you could push a new release compatible with the 7.0 version.

Thank you.

How do I send a tweet with an emoji?

Haven't found how to do so.

The Can_parse_multibyte_entities() unit test definitely shows that tweets with emoji can be read :), but how do I send one with an emoji in it?

Using the official Twitter API (https://github.com/twitter/twemoji), for example, I can replace the thumb up emoji with 👍. I just haven't found how to send this html fragment with the tweetmoasharp library. Or is there an easier way?

Thanks!

Retweet with Quote (Embedded Tweet)

Twitter have just added support for retweeting and quoting the original tweet as an embedded status, which saves characters in the retweet. We should find out what, if anything, is required to support this and implement it.

Issus in Nuget package?

Since Nuget Update to 3.1 i got errors on UAP-Projects while Newtonsoft.Json it self is installed with nuget. U can simply reproduce it:

  • Create new UAP-Projects in VS2015 (RTM)
  • Install Newtonsoft.Json with nuget (atm 7.0.1)
  • Install TweetMoaSharp
  • Run

Sorry for the german Error-Messages :)

error

JSON parsing error with ListSuggestedUsers?

Hi -

This snippet crashes with a JSON error.

ListSuggestedUsersOptions opt = new ListSuggestedUsersOptions();
opt.Lang = "en";
var c = service.ListSuggestedUsers(opt);

Thank you!

(Maybe) tweet.IsRetweeted and tweet.IsFavorited don't work

                        bool Retweeted = tweet.IsRetweeted;
                        bool Favorited = tweet.IsFavorited;

these are always return 'false' though I did retweet.
is this incorrect use?

and how can i load mute list?
'TwitterService.ListMutedUsers' returns 'long' type unlike 'TwitterService.ListBlockedUsers'.

:)
sorry for my terrible English

Chunked Media Upload - "Could not authenticate you"

Hi,

I've been trying to upload a gif image in a chunk based approach in the following way:
`var service = new TwitterService(_consumer_key, _consumer_secret);
service.AuthenticateWith(AccessToken, AccessTokenSecret);

var cMediares = await service.UploadMediaInitAsync(new UploadMediaInitOptions() { "image/gif", TotalBytes = 38656, MediaCategory = TwitterMediaCategory.AnimatedGif});`

But in response i'm getting an error, '32: "Could not authenticate you."' at service.UploadMediaInitAsync call.

Your kind help will be much appreciated.
Thanks.

Video's in Direct Messages

This bug has been in Tweetsharp since way back. If you send someone a video via DM, it can't be deserialized properly, throws the error

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'TweetSharp.TwitterDirectMessage' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.