Skip to content

Instantly share code, notes, and snippets.

@irwinwilliams
Created October 19, 2019 20:07
Show Gist options
  • Save irwinwilliams/4d6d765b2da6464af2a3fbc6fac00648 to your computer and use it in GitHub Desktop.
Save irwinwilliams/4d6d765b2da6464af2a3fbc6fac00648 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace TweetWhisperer.Function
{
public static class TwitterFavoritesReader
{
static readonly HttpClient client = new HttpClient();
[FunctionName("TwitterFavoritesReader")]
public static async Task Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger log,
ExecutionContext context)
{
var config = GetConfig(context);
var token = config["TwitterAccessToken"] ?? await GetToken(config["TwitterKey"], config["TwitterSecret"]);
var screenName = config["ScreenName"];
//TODO: ONLY GET last minute of faves
var uri = $"https://api.twitter.com/1.1/favorites/list.json?count=5&screen_name={screenName}";
var authHeader = System.Convert.ToBase64String(
new UTF8Encoding().GetBytes(token));
try
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
}
catch (Exception err)
{
log.LogError(err, "it happened");
}
var favoritesResponse = await client.GetAsync(uri);
var favesJson = await favoritesResponse.Content.ReadAsStringAsync();
var faves = JsonConvert.DeserializeObject<List<TwitterFave>>(favesJson);
await CategorizeThem(config, faves, log);
log.LogInformation(faves.Count()+" favorites found");
}
private static async Task CategorizeThem(IConfigurationRoot config, List<TwitterFave> faves, ILogger log)
{
var uri = config["CategorizeThemUrl"];
var keepItResponse = await client.PostAsJsonAsync(uri, faves);
var resp = await keepItResponse.Content.ReadAsStringAsync();
log.LogTrace("Was it kept??? " + resp);
}
private static IConfigurationRoot GetConfig(ExecutionContext context)
{
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
return config;
}
private static async Task<string> GetToken(string key, string secret)
{
var uri = "https://api.twitter.com/oauth2/token";
var bearerTokenCredentials = $"{key}:{secret}";
var authHeader = "Basic "+System.Convert.ToBase64String(
new UTF8Encoding().GetBytes(bearerTokenCredentials));
client.DefaultRequestHeaders.Add("Authorization", authHeader);
var nameValuePair = new KeyValuePair<string, string>("grant_type", "client_credentials");
var encodedContent = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>>{nameValuePair});
var result = await client.PostAsync(uri, encodedContent);
var resultContent = await result.Content.ReadAsStringAsync();
var e = JsonConvert.DeserializeObject<AccessTokenHolder>(resultContent);
return e.access_token;
}
}
public class AccessTokenHolder
{
public string token_type { get; set; }
public string access_token { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment