Random Hashtag Tweeting with Tweepy

  • Share this:

Code introduction


This function uses the Tweepy library to authenticate a Twitter account and randomly selects a hashtag to post on Twitter.


Technology Stack : Tweepy, Python

Code Type : Twitter API Automation

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 = ['#python', '#coding', '#tweepy', '#machinelearning', '#ai', '#data']
    random_hashtag = random.choice(hashtags)

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