Building a Twitter-AI Agent with n8n FastAPI and Tweepy

Want to streamline your Twitter engagement? Discover how to effortlessly post tweets using a FastAPI Tweet Posting API and n8n workflow automation. This post covers setting up Twitter API credentials, creating the API with FastAPI, and integrating with AI agents for dynamic content. Unlock automa...

Building a Twitter-AI Agent with n8n FastAPI and Tweepy

Sometimes I want to share content quickly on Twitter without worrying about truncating it, adding tags or staying within character limits. That's where AI agents come in handy. I use n8n, an open source workflow automation tool, along with the Twitter API to make this effortless. If you prefer a cloud-based solution, you can achieve the same with make.com.

In this blog post, I'll dive into creating a Tweet Posting API using FastAPI and Tweepy, focusing on how to integrate this setup with n8n for workflow automation and use an AI agent to dynamically generate tweet content.

Outline

  1. Prerequisites
  2. Obtaining Twitter API Credentials
  3. Setting Up the FastAPI Tweet Posting API
  4. Integrating with n8n for Workflow Automation
  5. Test it

1. Prerequisites

Before diving in, ensure you have the following:

  • FastAPI and Tweepy libraries set up with your Tweet Posting API.
  • Twitter Developer Account with a registered application to obtain API credentials.
  • n8n installed and configured. Refer to the n8n Installation Guide if you haven't set it up yet.
  • An OpenAI API Key or access to another AI service if you intend to use AI-generated content within n8n.

2. Obtaining Twitter API Credentials

To interact with Twitter's API, you need specific credentials. Here's a streamlined process to obtain them:

  1. Access the Twitter Developer Portal:
    Navigate to the Twitter Developer Portal and log in with your Twitter account.
  2. Create or Select a Project and App:
    • If you haven't created a project yet, click on "Create Project" and follow the prompts.
    • Within your project, select or create an App. This app will be used to interact with Twitter's API.
  3. Navigate to Keys and Tokens:
    In your app's dashboard, go to the "Keys and tokens" section to find your API KeyAPI Secret Key,  Access Token, and Access Token Secret. Ensure you keep these credentials secure.

Here's a brief explanation of why these credentials are needed.

  1. API Key (Consumer Key):
    • Identifies your application.
  2. API Secret Key (Consumer Secret):
    • Secures your application's interactions.
  3. Access Token:
    • Represents the user's authorization.
  4. Access Token Secret:
    • Secures the access token.
Note: These credentials allow your app to act specifically for the authenticated user. Ensure they are stored securely.

For detailed management of your projects and apps, visit the Twitter Developer Portal.

3. Setting Up the FastAPI Tweet Posting API

Assuming you have your FastAPI application set up with Tweepy as detailed earlier, ensure it's running and accessible.

Here's a quick recap of the essential parts:

# main.py

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import tweepy
import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

app = FastAPI(title="Tweet Posting API")

# Initialize Tweepy client with Twitter API credentials
client = tweepy.Client(
    consumer_key=os.getenv("CONSUMER_KEY"),
    consumer_secret=os.getenv("CONSUMER_SECRET"),
    access_token=os.getenv("ACCESS_TOKEN"),
    access_token_secret=os.getenv("ACCESS_TOKEN_SECRET")
)

print("Loading with credentials...")
try:
    # Verify Twitter Authentication
    me = client.get_user(username=os.getenv("TWITTER_USERNAME"))  # Ensure TWITTER_USERNAME is set in .env
    print("Twitter Authentication OK")
except Exception as e:
    print(f"Error during Twitter authentication: {str(e)}")

class Tweet(BaseModel):
    text: str

@app.post("/tweet")
async def create_tweet(tweet: Tweet):
    try:
        # Create a new tweet with the provided text
        response = client.create_tweet(text=tweet.text)
        return {"message": "Tweet posted!", "id": str(response.data['id'])}
    except tweepy.TweepyException as e:
        # Handle errors specific to Tweepy
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        # Handle general errors
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/health")
async def health():
    return {"status": "alive"}

Ensure your .env file contains the necessary credentials:

CONSUMER_KEY=your_consumer_key
CONSUMER_SECRET=your_consumer_secret
ACCESS_TOKEN=your_access_token
ACCESS_TOKEN_SECRET=your_access_token_secret
TWITTER_USERNAME=your_twitter_username

Run your FastAPI server:

uvicorn main:app --reload

Your API should now be running at http://localhost:8000.

4. Integrating with n8n for Workflow Automation

4.1 Introduction to n8n

n8n is an extendable workflow automation tool that allows you to connect various services and automate tasks without extensive coding. It supports a wide range of integrations, making it ideal for connecting your Tweet Posting API with other services like AI agents.

4.2 Set up the Agent workflow with Twitter

To enable n8n to send tweets via your FastAPI Tweet Posting API, follow these steps:

Create a New Workflow

  1. Add an AI Agent and configure OpenAI

Add a new chat model. I use GPT 4o-mini, and it works well for this use case.

  1. Add an an HTTP Request Node:

Select the HTTP Request tool type.

Ensure that n8n can access your FastAPI server (in the example below the FastAPI App is running at localhost:8000)

Ensure your Tweet server is up and accessible on the specified host and. port.

4.3 Test it

Looks Good. Let's check in x.com

Well done, GPT😄

We can now test the workflow by chatting with OpenAI and asking it to create a Twitter account for any topic you choose.

Wrap up

Integrating your FastAPI Tweet Posting API with n8n and an AI agent like OpenAI's GPT opens up powerful automation possibilities. By setting up a seamless workflow, you can generate and post engaging tweets automatically, enhancing your social media presence with minimal manual intervention.

For more detailed information on n8n's capabilities and additional integrations, explore the n8n Documentation.

Happy automating!

Data Privacy | Imprint