3 min read

Twitter/X API Interaction with Tweepy

This guide demonstrates how to interact with the Twitter (now X) API using the tweepy library. It covers authentication using API v2 (Client) to post tweets and fetch user information.

Modules Used:

  • tweepy: An easy-to-use Python library for accessing the Twitter API.
  • python-dotenv: To securely manage API keys and tokens.
  • argparse: To handle command-line arguments.

Prerequisites

  1. Twitter Developer Account: Apply for a developer account at developer.twitter.com.
  2. Project & App: Create a Project and an App in the developer portal.
  3. User Authentication Settings: Enable "Read and Write" permissions for your app if you want to post tweets.
  4. Keys & Tokens: Generate the following:
    • Consumer Key (API Key)
    • Consumer Secret (API Secret)
    • Access Token
    • Access Token Secret
    • Bearer Token (Optional for some read-only endpoints, but Client uses the keys/tokens for user context)

Installation

pip install tweepy python-dotenv

Setup

Create a .env file in your project directory:

TWITTER_API_KEY=your_consumer_key
TWITTER_API_SECRET=your_consumer_secret
TWITTER_ACCESS_TOKEN=your_access_token
TWITTER_ACCESS_SECRET=your_access_token_secret
TWITTER_BEARER_TOKEN=your_bearer_token

The Code

Save this as twitter_tool.py.

import tweepy
import os
import argparse
import sys
from dotenv import load_dotenv

# Load Config
load_dotenv()

# V2 API Client
client = tweepy.Client(
    bearer_token=os.getenv("TWITTER_BEARER_TOKEN"),
    consumer_key=os.getenv("TWITTER_API_KEY"),
    consumer_secret=os.getenv("TWITTER_API_SECRET"),
    access_token=os.getenv("TWITTER_ACCESS_TOKEN"),
    access_token_secret=os.getenv("TWITTER_ACCESS_SECRET")
)

def post_tweet(text):
    print(f"Posting tweet: '{text}'...")
    try:
        response = client.create_tweet(text=text)
        print(f"Success! Tweet ID: {response.data['id']}")
    except tweepy.TweepyException as e:
        print(f"Error posting tweet: {e}")

def get_user_info(username):
    print(f"Fetching info for @{username}...")
    try:
        # user_fields expands the default data returned
        response = client.get_user(username=username, user_fields=['description', 'public_metrics'])
        user = response.data

        if user:
            print(f"\n--- User: {user.name} (@{user.username}) ---")
            print(f"ID: {user.id}")
            print(f"Bio: {user.description}")
            metrics = user.public_metrics
            print(f"Followers: {metrics['followers_count']}")
            print(f"Following: {metrics['following_count']}")
            print(f"Tweets: {metrics['tweet_count']}")
        else:
            print("User not found.")

    except tweepy.TweepyException as e:
        print(f"Error fetching user: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Twitter/X API Tool with Tweepy")
    subparsers = parser.add_subparsers(dest="command", help="Command to run")

    # Post Command
    post_parser = subparsers.add_parser("post", help="Post a new tweet")
    post_parser.add_argument("text", help="The text content of the tweet")

    # User Info Command
    user_parser = subparsers.add_parser("user", help="Get user information")
    user_parser.add_argument("username", help="Twitter username (without @)")

    args = parser.parse_args()

    if args.command == "post":
        post_tweet(args.text)
    elif args.command == "user":
        get_user_info(args.username)
    else:
        parser.print_help()

Usage

# Post a tweet
python twitter_tool.py post "Hello world from Python! <a href='/?search=%23coding' class='obsidian-tag'>#coding</a>"

# Get user stats
python twitter_tool.py user elonmusk

programming/python/python