Skip to content

Instantly share code, notes, and snippets.

@rfennell
Created July 14, 2023 12:24
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 rfennell/d9d89f65725f2a74a21845ae90468e27 to your computer and use it in GitHub Desktop.
Save rfennell/d9d89f65725f2a74a21845ae90468e27 to your computer and use it in GitHub Desktop.
Azure Function code to send a Tweet to the V2 Twitter API using OAUTH1.0
#r "Newtonsoft.Json"
using System.Text;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using OAuth;
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function to send a Tweet.");
string oauth_consumer_key = Environment.GetEnvironmentVariable("oauth_consumer_key");
string oauth_consumer_secret = Environment.GetEnvironmentVariable("oauth_consumer_secret");
string oauth_token = Environment.GetEnvironmentVariable("oauth_token");
string oauth_token_secret = Environment.GetEnvironmentVariable("oauth_token_secret");
string url = "https://api.twitter.com/2/tweets";
string tweet = req.Query["tweet"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
tweet = tweet ?? data?.tweet;
log.LogInformation($"Message:{tweet}");
var oauth = new OAuthMessageHandler(oauth_consumer_key, oauth_consumer_secret, oauth_token, oauth_token_secret);
var tweetData = new { text = tweet };
var jsonData = JsonConvert.SerializeObject(tweetData);
var createTweetRequest = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(jsonData, Encoding.UTF8, "application/json")
};
using var httpClient = new HttpClient(oauth);
var response = await httpClient.SendAsync(createTweetRequest);
log.LogInformation("Tweet sent successfully!");
return new OkObjectResult("Tweet sent successfully!");
}
@rfennell
Copy link
Author

Note that for this to work you also need a function.proj file upload that adds the reference to OAuth.net

    <Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
      </PropertyGroup>

      <ItemGroup>
        <PackageReference Include="OAuth.net" Version="1.7.0" />
      </ItemGroup>
    </Project>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment