Random Hashtag Selection from User#s Tweets

  • Share this:

Code introduction


This function extracts a random number of hashtags from the recent 50 tweets of a specified Twitter user, which also appear in the user's other tweets.


Technology Stack : Tweepy, random selection, Twitter API

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def tweet_random_hashtags(user_id, num_hashtags):
    import tweepy
    import random
    
    # Authenticate to Twitter
    auth = tweepy.OAuthHandler("CONSUMER_KEY", "CONSUMER_SECRET")
    auth.set_access_token("ACCESS_TOKEN", "ACCESS_TOKEN_SECRET")
    
    # Create API object
    api = tweepy.API(auth)
    
    # Fetch the user's recent tweets
    tweets = api.user_timeline(user_id=user_id, count=50)
    
    # Extract hashtags from tweets
    hashtags = set()
    for tweet in tweets:
        hashtags.update(tweepy.parse hashtags(tweet.text))
    
    # Randomly select hashtags
    selected_hashtags = random.sample(hashtags, num_hashtags)
    
    return selected_hashtags