Random Quote Tweeting from User#s Tweets

  • Share this:

Code introduction


This function randomly selects a quote from a specified Twitter user's tweets that contains 'quote' and posts it to the user's main page using the Tweepy library.


Technology Stack : Tweepy

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import tweepy
import random

def tweet_random_quote(user_id):
    """
    This function tweets a random quote from a user's tweets.
    """
    # Authenticate to Twitter API
    auth = tweepy.OAuthHandler('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET')
    auth.set_access_token('YOUR_ACCESS_TOKEN', 'YOUR_ACCESS_TOKEN_SECRET')
    api = tweepy.API(auth)

    # Fetch user's tweets
    tweets = api.user_timeline(user_id=user_id, count=10, tweet_mode='extended')

    # Extract quotes from tweets
    quotes = [tweet.full_text for tweet in tweets if 'RT' not in tweet.full_text and 'quot' in tweet.full_text.lower()]

    # Tweet a random quote
    if quotes:
        random_quote = random.choice(quotes)
        api.update_status(random_quote)
        return f"Tweeted: {random_quote}"
    else:
        return "No quotes found for the user."

# Usage example
# print(tweet_random_quote('123456789'))                
              
Tags: