Tweeting a Random New York Hashtag Using Tweepy

  • Share this:

Code introduction


This function uses the Tweepy library to authenticate with the Twitter API, then randomly selects a hashtag related to 'New York', and uses it to post a tweet.


Technology Stack : Tweepy

Code Type : Twitter API call

Code Difficulty : Intermediate


                
                    
import tweepy
import random

def tweet_random_hashtag(api_key, api_secret_key, access_token, access_token_secret):
    # Authenticate to Twitter
    auth = tweepy.OAuthHandler(api_key, api_secret_key)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    # Generate a random hashtag
    hashtags = api.get_place_hashtags(query='New York', count=10)
    random_hashtag = random.choice(hashtags['hashtags'])['text']

    # Tweet the random hashtag
    api.update_status(f'Check out this random hashtag: #{random_hashtag}')                
              
Tags: