Python Script to Auto Like a Tweet

Have you ever been exhausted by liking so many peoples tweets that you’ve wondered if there is a better and faster way? Well now you can create a Python script to auto like a tweet based on multiple Twitter accounts. Give your thumb a break and learn how to code today!

Let’s review the basics. First, you will need to have a working installation of Python and download the Tweepy library using PIP. If that last sentence made no sense to you, no problem, check out this getting started article. Also, you’ll need to create a Twitter app before implementing the below code. The above link describes how to generate unique consumer and token keys to interface with Twitter’s API.

Once we have installed Python (I’m using version 3) and the required library, we are ready to begin. Open up a new Python file and copy the following code:

import tweepy
import time
import random
import datetime



#time.sleep(random.randint(1,1800))
accounts = ['@micahvorst']
logFile = '//home//pi//Documents//socialTwitterBot//logs.txt'

consumer_key = 'c key'
consumer_secret = 'c secret'
access_token = 'a token'
access_token_secret = 'a secret'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

user = api.me()

# Open log file.
logs = open(logFile, 'a')

for account in accounts:
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H %M %S')
    try:
        #time.sleep(random.randint(1,20))
        tweets = api.user_timeline(screen_name=account, count=1)
        tweet = tweets[0]
        api.create_favorite(tweet.id)
        print("Liking tweet {} of {}".format(tweet.id, tweet.author.name))
        logs.write('{}: Liking tweet {} of {}.\n'.format(st, tweet.id, tweet.author.name))
    except:
        print("Already liked {}.".format(tweet.author.name))
        logs.write('{}: Already liked {} for the day.\n'.format(st, tweet.author.name))
        
logs.close()

Based on the above code we use the Tweepy library to create the Twitter session. You can expand the ‘accounts’ list variable to include all accounts that you wish to scroll through and like. This code will search for the latest post on the users timeline and attempt to like the Tweet. If it has already been liked by your account it will alert you that the Tweet has already been liked.

You’ll also notice that I’ve implemented a simple logging system so that we can review our logs in the future to confirm that the script is continuing to work as expected.

Like with implementing the joke Python Twitter bot we can create a scheduled task to run this bot once a day, etc…

Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.