Skip to content

Instantly share code, notes, and snippets.

@RobertTLange
Last active November 15, 2024 17:09
Show Gist options
  • Save RobertTLange/5124138e241bbaa0689443561504b2f9 to your computer and use it in GitHub Desktop.
Save RobertTLange/5124138e241bbaa0689443561504b2f9 to your computer and use it in GitHub Desktop.
Twitter API Example
import tweepy
import os
from typing import List, Optional
class TwitterClient:
def __init__(
self,
consumer_key: str,
consumer_secret: str,
access_token: str,
access_token_secret: str,
):
"""Initialize Twitter API client."""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
self.client = tweepy.Client(
consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token=access_token,
access_token_secret=access_token_secret,
)
self.api = tweepy.API(auth)
def upload_media(self, image_paths: List[str]) -> List[str]:
"""Upload images to Twitter and return media IDs."""
media_ids = []
for image_path in image_paths:
if not os.path.exists(image_path):
raise FileNotFoundError(f"Image not found: {image_path}")
# Upload media and get ID
media = self.api.media_upload(filename=image_path)
media_ids.append(media.media_id_string)
return media_ids
def post_tweet(
self,
text: str,
image_paths: Optional[List[str]] = None,
reply_to: Optional[str] = None,
) -> dict:
"""Post a tweet with optional images and reply."""
# Upload images if provided
media_ids = None
if image_paths:
media_ids = self.upload_media(image_paths)
# Create tweet
response = self.client.create_tweet(
text=text, media_ids=media_ids, in_reply_to_tweet_id=reply_to
)
return response.data
def create_thread(
client: TwitterClient,
tweets: List[str],
image_paths: Optional[List[List[str]]] = None,
) -> List[dict]:
"""Create a thread of tweets."""
responses = []
previous_tweet_id = None
# Validate image_paths length if provided
if image_paths and len(image_paths) != len(tweets):
raise ValueError("image_paths length must match tweets length")
for i, tweet in enumerate(tweets):
# Get images for current tweet if available
tweet_images = image_paths[i] if image_paths else None
# Post tweet and save response
response = client.post_tweet(
text=tweet, image_paths=tweet_images, reply_to=previous_tweet_id
)
responses.append(response)
# Save tweet ID for reply chain
previous_tweet_id = response["id"]
return responses
if __name__ == "__main__":
# Initialize client
twitter = TwitterClient(
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_TOKEN_SECRET"),
)
# Post single tweet with image
response = twitter.post_tweet(
text="""🐦 Playing around with the X/Twitter API in Python!
Check out the example gist for posting a tweet with an image here:
πŸ“ https://gist.github.com/RobertTLange/5124138e241bbaa0689443561504b2f9
Automation is so much fun πŸš€
Brought to you with some @cursor_ai support πŸ€–""",
image_paths=["twitter_python_api.png"],
)
# # Create thread with different images for each tweet
# tweets = [
# "1/3 Starting a thread about coding...",
# "2/3 Here's an interesting fact...",
# "3/3 Thanks for reading!",
# ]
# responses = create_thread(
# client=twitter,
# tweets=tweets,
# image_paths=[
# ["path/to/image1.jpg"],
# ["path/to/image2.jpg"],
# ["path/to/image3.jpg"],
# ],
# )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment