Skip to content

Instantly share code, notes, and snippets.

@AndyM84
Created April 17, 2016 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndyM84/02f2840e46dd665db748552f6dfbcc5e to your computer and use it in GitHub Desktop.
Save AndyM84/02f2840e46dd665db748552f6dfbcc5e to your computer and use it in GitHub Desktop.
#r "Newtonsoft.Json"
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
string TwitterKey = "";
string TwitterSecret = "";
log.Verbose($"Webhook was triggered!");
string jsonContent = await req.Content.ReadAsStringAsync();
dynamic data = JsonConvert.DeserializeObject(jsonContent);
if (data.id == null || data.handle == null)
{
return req.CreateResponse(HttpStatusCode.BadRequest, new {
error = "Please pass the user ID and Twitter handle properties in the input object"
});
}
var bearerToken = await GetBearerToken(TwitterKey, TwitterSecret);
if (string.IsNullOrEmpty(bearerToken))
{
return req.CreateResponse(HttpStatusCode.InternalServerError, new {
error = "Twitter failed to authenticate application, please check key/secret info and restart function."
});
}
// Added count=5 to help cut back on memory usage
string timelineUrl = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" + data.handle + "&count=5";
var timelineJson = await CallApi(timelineUrl, bearerToken);
if (string.IsNullOrEmpty(timelineJson))
{
return req.CreateResponse(HttpStatusCode.InternalServerError, new {
error = "User not found on Twitter or failed to make call to Twitter."
});
}
JArray timeline = JArray.Parse(timelineJson);
List<string> latestTweets = new List<string>();
for (int i = 0; i < timeline.Count() && i < 5; ++i)
{
JObject tweet = JObject.Parse(timeline[i].ToString());
latestTweets.Add(tweet["text"].ToString());
}
// TODO: Add code to save to db through API or other mechanism
return req.CreateResponse(HttpStatusCode.OK, new {
UserID = data.id,
Tweets = JsonConvert.SerializeObject(latestTweets)
});
}
public static async Task<string> GetBearerToken(string Key, string Secret)
{
string key = Uri.EscapeDataString(Key);
string secret = Uri.EscapeDataString(Secret);
byte[] encBytes = Encoding.UTF8.GetBytes(key + ":" + secret);
string encoded = Convert.ToBase64String(encBytes);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://api.twitter.com/oauth2/token");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + encoded);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
client.DefaultRequestHeaders.AcceptCharset.Add(new StringWithQualityHeaderValue("UFT-8"));
Dictionary<string, string> body = new Dictionary<string, string>();
body.Add("grant_type", "client_credentials");
HttpContent bodyContent = new FormUrlEncodedContent(body);
HttpResponseMessage respMsg = await client.PostAsync("https://api.twitter.com/oauth2/token", bodyContent);
if (respMsg.IsSuccessStatusCode)
{
var response = await respMsg.Content.ReadAsStringAsync();
dynamic json = JsonConvert.DeserializeObject(response);
return json.access_token;
}
return null;
}
public static async Task<string> CallApi(string Url, string BearerToken)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + BearerToken);
HttpResponseMessage respMsg = await client.GetAsync(Url);
if (respMsg.IsSuccessStatusCode)
{
return await respMsg.Content.ReadAsStringAsync();
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment