DEV Community

Cover image for Automating Twitter Engagement with Lyzr Automata and Streamlit

Posted on

Automating Twitter Engagement with Lyzr Automata and Streamlit

Social media presence is crucial for businesses and individuals alike. However, consistently creating engaging content can be time-consuming. That's where automation comes in handy. In this blog post, we'll explore how to automate tweet generation and posting using the Lyzr Automata.

How It Works
Topic Input: Users enter a topic of their choice into the Lyzr Tweet Blaster interface.
Tweet Generation: The application generates tweet ideas based on the provided topic using OpenAI's GPT-4 model. It presents the user with a selection of generated tweets to choose from.
Tweet Posting: Once the user selects a tweet, the application further refines it and ensures it meets specific criteria, such as engagement potential and character limit. Finally, it automatically posts the tweet to the user's Twitter account.

Example Usage
Let's say you want to tweet about "Artificial Intelligence." You input the topic into the Lyzr Tweet Blaster and click the "Get Tweets" button. The application generates several tweet ideas related to AI. After selecting the most compelling one, the application refines it and posts it to your Twitter account - all in a matter of seconds!

Setting Up the Environment
Before diving into the details, let's set up our environment. The Lyzr Tweet Blaster is built using Python and utilizes several libraries, including Streamlit for the user interface, OpenAI for text generation, and the tweet_tool module for posting tweets. Additionally, we use the dotenv module for managing API keys securely.


pip install lyzr_automata dotenv streamlit tweepy pydantic
Enter fullscreen mode Exit fullscreen mode

from pydantic import BaseModel
from typing import Optional
import tweepy
import os
from dotenv import load_dotenv


def post_tweet(tweet):
    client = tweepy.Client(consumer_key=os.getenv("CONSUMER_KEY"),

class TweetInput(BaseModel):
    tweet: str

class TweetOutput(BaseModel):
    success: bool
    message: Optional[str]
Enter fullscreen mode Exit fullscreen mode

from pydantic import BaseModel: Imports the BaseModel class for creating data models.
from typing import Optional: Imports the Optional type for indicating optional fields.
import tweepy: Imports the tweepy library for interacting with the Twitter API.
import os: Imports the os module for interacting with the operating system.
from dotenv import load_dotenv: Imports the load_dotenv function to load environment variables from a .env file

Loading Environment Variables:
load_dotenv(): This line loads environment variables from a .env file (likely containing your Twitter API credentials).

post_tweet Function:
Takes a single argument tweet which is expected to be a string representing the tweet content.
Creates a tweepy.Client object using your Twitter API credentials retrieved from environment variables.
Uses the client.create_tweet method to post the provided tweet to your Twitter account.

Data Models:
TweetInput: Defines a data model for the input data to the post_tweet function. It has a single field tweet (required) that represents the tweet content.
TweetOutput: Defines a data model for the output data of the post_tweet function (likely not used in this example).

from import Tool
from tweet import TweetOutput,TweetInput,post_tweet

def tweet_posting_tool():
    return Tool(
        name="LinkedIn Post",
        desc="Posts an post on linkedin provided details.",
Enter fullscreen mode Exit fullscreen mode

from import Tool: Imports the Tool class from the module. This class is likely used to represent a tool within Lyzr Automata.
from tweet import TweetOutput, TweetInput, post_tweet: Imports the TweetOutput, TweetInput data models, and the post_tweet function (assumed to be defined elsewhere, likely for posting tweets).

tweet_posting_tool function:
This function defines a new tool using the Tool class.
name: Sets the name of the tool to "LinkedIn Post" (although it's actually posting tweets).
desc: Provides a description for the tool: "Posts an post on linkedin provided details." (Note: There might be a typo, it should likely be "post" instead of "post on").
function: Specifies the function associated with the tool. Here, it's set to the post_tweet function, which is likely responsible for handling the actual tweet posting logic.
function_input: Defines the expected input data model for the tool. Here, it's set to TweetInput, indicating the tool expects data following the TweetInput structure (likely containing the tweet content).
function_output: Defines the output data model for the tool. Here, it's set to TweetOutput, indicating the tool might return data following the TweetOutput structure (possibly containing success status or error messages).
default_params: Sets any default parameters for the tool (an empty dictionary in this case).

import streamlit as st
import os
from dotenv import load_dotenv,find_dotenv
from lyzr_automata.ai_models.openai import OpenAIModel
from lyzr_automata import Agent,Task
from lyzr_automata.pipelines.linear_sync_pipeline import LinearSyncPipeline
from PIL import Image
from tweet_tool import tweet_posting_tool

open_ai_text_completion_model = OpenAIModel(
        "model": "gpt-4-turbo-preview",
        "temperature": 0.2,
        "max_tokens": 1500,

topics = st.text_input("Enter Your Topic")

def tweet_generator(topic):

    twitter_agent = Agent(
        role="Tweet Expert",
        prompt_persona=f"""You are a word class journalist and tweet influencer.
                write a viral tweeter thread about given topic using and following below rules:

    post_tweet = tweet_posting_tool()
    generate_topics = Task(
        name="Tweet Generator",
        instructions=f"""generate 20 topics Regarding {topic} and select 1 best topic from it.
        20 topics:
        Understanding word embeddings: algorithms, applications, and limitations.

    generate_tweet = Task(
        name="Tweet Generator",
        instructions=f"""write a viral tweeter thread about given topic and following below rules:
                1/ The thread is engaging and informative with good data.
                2/ Only generate 1 tweet
                3/ The thread need to address given topic very well.
                4/ The thread needs to be viral and atleast get 1000 likes.
                5/ The thread needs to be written in a way that is easy to read and understand.
                6/ Output is only threads no any other text apart from thread
                7/ The thread character is upto 200 characters not more than it.

                Ouput: OpenAI is reshaping our world with AI innovation, from ChatGPT to DALL·E. Their tech is not just about smarter machines, but about augmenting human creativity and solving complex problems. With a commitment to safety and ethics, OpenAI is leading us into a future where AI empowers everyone. Dive in to see how they're doing it. #OpenAI #Innovation #FutureIsNow 💡🤖✨

    review_task = Task(
        name="Tweet review",
        instructions=f"""Your task is to review generated tweet and check whether tweet is upto 200 characters if tweet is more than 200 characters than summarize it in 200 characters.
        [!Important]return Improved tweet upto 200 characters.Do not write Improved Tweet.

    post_task = Task(
        name="Tweet Posting",
    output = LinearSyncPipeline(
        name="Tweet Pipline",
        completion_message="pipeline completed",

    return output[2]['task_output']

if st.button("Get Tweets"):
    tweets = tweet_generator(topics)
    st.success(f"Tweet Uploaded Successfully!!")
Enter fullscreen mode Exit fullscreen mode

Setting Up:
Imports libraries like Streamlit, OpenAI, and tweet_tool.
Loads environment variables (likely API keys) securely using dotenv.
Creates an OpenAI model object for text generation using GPT-4.

tweet_generator Function:
Defines a function named tweet_generator that takes the user-provided topic as input.
Creates a "Tweet Expert" Agent within Lyzr Automata.
Creates a tweet posting tool instance (post_tweet).
Defines several Tasks:
Generate Topics: Uses the OpenAI model to generate 20 topics related to the input topic and selects the best one.
Generate Tweet: Uses the OpenAI model with the "Tweet Expert" persona to create a viral tweet thread based on the chosen topic, following specific criteria (engaging, informative, under 200 characters).
Review Tweet: Reviews the generated tweet and ensures it's within the character limit (200 characters), summarizing if needed.
Post Tweet: Uses the post_tweet tool to post the final tweet.
Creates a LinearSyncPipeline that executes these Tasks sequentially.

A button ("Get Tweets") triggers the tweet_generator function with the user's topic.
The generated tweet is displayed using Streamlit markdown (st.markdown).
A success message ("Tweet Uploaded Successfully!") appears upon successful posting (likely using the Twitter API through the post_tweet tool).

try it now:
For more information explore the website: Lyzr

Top comments (0)