Randomly Retrieve Hashtag Tweets from Twitter API

  • Share this:

Code introduction


This function is used to randomly retrieve tweets with a specific hashtag from the Twitter API.


Technology Stack : Tweepy

Code Type : Function

Code Difficulty : Intermediate


                
                    
def get_random_tweets(hashtag, count=10):
    import tweepy
    import random

    # 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)

    # Search for tweets with a specific hashtag
    tweets = tweepy.Cursor(api.search_tweets, q=hashtag, tweet_mode='extended').items(count)

    # Randomly select tweets from the search results
    random_tweets = random.sample(list(tweets), min(count, len(tweets)))

    # Return the selected tweets
    return [tweet.full_text for tweet in random_tweets]                
              
Tags: