Created
July 14, 2023 12:24
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that for this to work you also need a
function.proj
file upload that adds the reference to OAuth.net