umang
umang

Reputation: 29

How to post Special character tweet using asp.net API?

I m using Given below code to post the tweet on twitter. But when we upload it on the server then special character (!,:,$ etc) tweets not published on twitter. this code is working fine in the local system

string key = "";
string secret = "";
string token="";
string tokenSecret="";
try
{           
string localFilename = HttpContext.Current.Server.MapPath("../images/").ToString();

            using (WebClient client = new WebClient())
            {
                client.DownloadFile(imagePath, localFilename);
            }
            var service = new TweetSharp.TwitterService(key, secret);
            service.AuthenticateWith(token, tokenSecret);
            // Tweet wtih image
            if (imagePath.Length > 0)
            {
                using (var stream = new FileStream(localFilename, FileMode.Open))
                {
                    var result = service.SendTweetWithMedia(new SendTweetWithMediaOptions
                    {
                        Status = message,
                        Images = new Dictionary<string, Stream> { { "name", stream } }
                    });
                }                   
            }
            else // just message
            {
                var result = service.SendTweet(new SendTweetOptions
                {
                    Status = HttpUtility.UrlEncode(message)
                });
            } 

    }
    catch (Exception ex)
    {
        throw ex;
    }

Upvotes: 2

Views: 456

Answers (2)

Linvi
Linvi

Reputation: 2087

In addition to TweetMoaSharp you can use Tweetinvi with the following code:

var binary = File.ReadAllBytes(@"C:\videos\image.jpg");
var media = Upload.UploadMedia(binary);

var tweet = Tweet.PublishTweet("hello", new PublishTweetOptionalParameters
{
    Medias = {media}
});

Upvotes: 0

Yort
Yort

Reputation: 787

The statuses/update_with_media API endpoint is actually deprecated by Twitter and shouldn't be used (https://dev.twitter.com/rest/reference/post/statuses/update_with_media).

TweetSharp also has some issues with using this method when the tweet contains both a 'special character' AND an image (works fine with either, but not both). I don't know why and I haven't been able to fix it, it's something to do with the OAuth signature I'm pretty sure.

As a solution I suggest you use TweetMoaSharp (a fork of TweetSharp). It has been updated to support the new Twitter API's for handling media in tweets, and it will work in this situation if you use the new stuff.

Basically you upload each media item using a new UploadMedia method, and that will return you a 'media id'. You then use the normal 'SendTweet' method and provide a list of the media ids to it along with the other status details. Twitter will attach the media to the tweet when it is posted, and it will work when there are both special characters and images.

Upvotes: 1

Related Questions