Write a Python script that connects to the Twitter API, streams tweets containing a specified keyword in real-time, and stores the tweet text and metadata in a PostgreSQL database.
PLAINFORMAT
import tweepy
from tweepy import StreamListener
import psycopg2

# Replace these with your own Twitter API credentials
consumer_key = "your_consumer_key"
consumer_secret = "your_consumer_secret"
access_token = "your_access_token"
access_token_secret = "your_access_token_secret"

# Replace these with your own PostgreSQL connection details
db_host = "your_db_host"
db_port = "your_db_port"
db_name = "your_db_name"
db_user = "your_db_user"
db_password = "your_db_password"

# Keyword to track on Twitter
keyword = "example_keyword"

# Connect to PostgreSQL database
conn = psycopg2.connect(
    host=db_host,
    port=db_port,
    dbname=db_name,
    user=db_user,
    password=db_password
)
cur = conn.cursor()

# Create table if it doesn't exist
cur.execute("""
CREATE TABLE IF NOT EXISTS tweets (
    id SERIAL PRIMARY KEY,
    created_at TIMESTAMP,
    text TEXT,
    username VARCHAR(255),
    description TEXT,
    location TEXT,
    followers_count INTEGER,
    friends_count INTEGER,
    statuses_count INTEGER
);
""")
conn.commit()


class MyStreamListener(StreamListener):
    def on_status(self, status):
        # Extract tweet data
        created_at = status.created_at
        text = status.text
        username = status.user.screen_name
        description = status.user.description
        location = status.user.location
        followers_count = status.user.followers_count
        friends_count = status.user.friends_count
        statuses_count = status.user.statuses_count

        # Insert tweet data into PostgreSQL database
        cur.execute("""
            INSERT INTO tweets (created_at, text, username, description, location, followers_count, friends_count, statuses_count)
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s);
        """, (created_at, text, username, description, location, followers_count, friends_count, statuses_count))
        conn.commit()

    def on_error(self, status_code):
        if status_code == 420:
            return False


# Authenticate with Twitter API
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

# Start streaming tweets containing the specified keyword
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener)
myStream.filter(track=[keyword])