Software Architect / Microsoft MVP (AI) and Technical Author

AI, Azure, Azure Functions, C#, Chat GPT, OpenAI, Prototyping, Social Opinion API, Twitter API v2

How To Build an AI Bot using Azure Functions, Chat GPT and the Twitter API v2 with C#

Chat GPT is everywhere at the moment.  I’ve been digging into the APIs and playing around with the endpoints.

In this guide, you’ll see how to build a Twitter bot using an Azure Function and Chat GPT in C#.

The bot will generate tweets from a single prompt using Chat GPT Completions endpoint and post these to Twitter.

It’ll take less than an hour.

Required NuGet Packages

The following NuGet packages are used to connect to the Twitter API v2 and Chat GPT:

  • Social Opinion API
  • OpenAI.GPT3

 

Download the Social Opinion NuGet package here.  Download the Chat GPT NuGet package from Betalgo here.

Process and Configuration

The process is relatively straightforward and as follows:

  1. Construct a request for the Chat GPT Completions endpoint
  2. Send the request using the Chat GPT NuGet package
  3. Parse the text response
  4. Create a tweet using the text response for Chat GPT
  5. Send the Tweet using the Social Opinion NuGet package

 

The following sequence diagram shows this in action:

Creating the Chat GPT Request

To generate text using the Chat GPT Completions endpoint, you need an API Key.  You can do this by visiting your developer profile at Open AI:

After fetching your API Key, the following steps are performed in the code:

 

  1. Construct a CompletionCreateRequest
  2. Seed the prompt with a phrase
  3. Specify the max number of tokens and language model you want to use
  4. Send the request and parse the result

 

This code is encapsulated within a method CreateTweetUsingOpenAI :

private static async Task<string> CreateTweetUsingOpenAI()
{
OpenAIService service = new OpenAIService(new OpenAI.GPT3.OpenAiOptions
  {
    ApiKey = "YOUR-OPEN-API-KEY"
  });

var completionResult = await service.Completions.CreateCompletion(new CompletionCreateRequest

{
  Prompt = "Write a funny but true observation about software development tweet in 280 characters or less.  Do not include hashtags.",
  MaxTokens = 280,
  LogProbs = 1,
  Model = Models.TextDavinciV3
});
if (completionResult.Successful)
{
  return completionResult.Choices.FirstOrDefault().Text;
}
else
{
if (completionResult.Error == null)
{
  throw new Exception("Unknown Error");
}
  Console.WriteLine($"{completionResult.Error.Code}: {completionResult.Error.Message}");
}
  return completionResult.Choices.FirstOrDefault().Text;
}

 

The generated text from the above method is then returned to the caller.

Posting the Tweet

The method PostTweet accepts the content to post on Twitter and simple posts it.

The OAuth object is instantiated with the relevant keys :

private static Task<TweetModel> PostTweet(string tweetContent)
{
  string consumerKey = "YOUR_CONSUMER_KEY";
  string consumerSecret = " YOUR_CONSUMER_SECRET";
  string accessToken = " YOUR_ACCESS_TOKEN";
  string accessTokenSecret = " YOUR_ACCESS_TOKEN_SECRET";

TweetService service = new TweetService(new SocialOpinionAPI.Core.OAuthInfo
{
  AccessSecret = accessTokenSecret,
  AccessToken = accessToken,
  ConsumerKey = consumerKey,
  ConsumerSecret = consumerSecret
});
return Task.FromResult(service.PostTweetV1(tweetContent));
}

 

You can obtain the keys for your account by visiting https://developer.twitter.com :

A serialized tweet model is returned to the caller:

 

{
    "data": {
        "author_id": null,
        "created_at": "2023-03-13T10:49:08",
        "id": "1635231512579678208",
        "lang": "en",
        "possibly_sensitive": false,
        "source": "<a href=\"https://socialopinion.co.uk/\" rel=\"nofollow\">DeveloperFun</a>",
        "text": "Software development: It's so complex, it feels like we're trying to unravel an endless ball of tangled yarn, but l… https://t.co/E2UYqxGMi9"
    },
    "includes": null
}

 

Azure Function

A single Azure function invokes each of the above methods.  The code is relatively straight forward and uses the default Azure Function project template in Visual Studio 2020 :

[FunctionName("GenerateTweet")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function,
                                                    "get","post", Route = null)] HttpRequest req,
                                                    ILogger log)

{
try
{
  log.LogInformation("C# HTTP trigger function processed a request.");
  string tweet = await CreateTweetUsingOpenAI();
  var tweetModel = await PostTweet(tweet);
  return new OkObjectResult(JsonConvert.SerializeObject(tweetModel));
}
catch(Exception ex)
{
  return new BadRequestObjectResult(ex.Message);
}
}

 

In the above code, the function accepts and POST or GET.  The tweet is generated using Open AI and then posted to Twitter.

Demo

You can see a demo of this in action here. In this demo, you’ll see a POST being sent using Postman to a locally running instance of the Azure Function.

The function is invoked, and content generated using AI is automatically posted to Twitter:

Ideas, Further Reading, and Resources

Some notes from the above code:

  • API keys and secrets have been hard coded. You don’t really want to do this. Store these in Azure Key Vault and read from there.
  • The Chat GPT prompt is also hard coded. Introduce configuration to make this more dynamic.
  • The Azure Function could be run on a Timer Trigger as opposed to an HTTP Trigger.
  • Run the Azure Function at specific periods to schedule content.

 

For tips on how to implement the above read the useful links that follow.

Useful Links:

 

Summary

There are loads of possibilities with the Open AI APIs and generative AI. Mesh them with different APIs and web services to help create innovative solutions.  How will you use them?

JOIN MY EXCLUSIVE EMAIL LIST
Get the latest content and code from the blog posts!
I respect your privacy. No spam. Ever.

2 Comments

  1. Jodie

    I am now not certain the place you are getting your info,
    however good topic. I must spend some time learning more or
    figuring out more. Thank you for great info I used to be searching for this information for my mission.

  2. ChatGPT

    Awesome tutorial! I found it really helpful and easy to follow. The step-by-step guide made it easy for me to understand how to build an AI bot using Azure Functions Chat, GPT, and the Twitter API v2 with C#. Thank you so much for sharing this valuable information with us. Looking forward to reading more of your tutorials in the future. Great job! – Alex Cool

Leave a Reply