Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class TwitterService : ITwitterService
{
public string ObtainBearerToken(string consumerKey, string consumerSecret)
{
var applicationAuthorization = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Uri.EscapeDataString(consumerKey), Uri.EscapeDataString(consumerSecret))));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.twitter.com/oauth2/token");
request.Headers.Add("Authorization", "Basic " + applicationAuthorization);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
request.AutomaticDecompression = DecompressionMethods.GZip;
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write("grant_type=client_credentials");
}
WebResponse response = request.GetResponse();
var token = "";
using (var reader = new StreamReader(response.GetResponseStream()))
{
token = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject<Token>(token).access_token;
}
public async Task<List<Tweet>> RetrieveTweetsAsync(TwitterOptions options)
{
var tweets = new List<Tweet>();
if (!string.IsNullOrEmpty(options.Username) && !string.IsNullOrEmpty(options.ConsumerKey) && !string.IsNullOrEmpty(options.ConsumerSecret))
{
var bearerToken = ObtainBearerToken(options.ConsumerKey, options.ConsumerSecret);
var timelineUrl =
string.Format("https://api.twitter.com/1.1/statuses/user_timeline.json?exclude_replies={0}&screen_name={1}",
"false",
Uri.EscapeDataString(options.Username));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(timelineUrl);
request.Headers.Add("Authorization", "Bearer " + bearerToken);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
request.AutomaticDecompression = DecompressionMethods.GZip;
WebResponse response = await request.GetResponseAsync();
string responseData = await new StreamReader(response.GetResponseStream()).ReadToEndAsync();
var jsonResponse = JsonConvert.DeserializeObject<IEnumerable<TweetRaw>>(responseData);
tweets = jsonResponse.Select(t =>
new Tweet() { Message = t.text,
Username = t.user.screen_name,
Avatar = t.user.profile_image_url,
Timestamp = DateTime.ParseExact(t.created_at, "ddd MMM dd HH:mm:ss %zzzz yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal).ToFriendlyDate(),
Id = t.id_str
}).ToList();
}
return tweets;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment