Automating Twitter Followers Count

Subscribe to my newsletter and never miss my upcoming articles

I've seen many people on Twitter where they append followers count to their name and the counter increments or decrements based on followers count.

This is how it looks - To test more on this implementation, check my profile๐Ÿ˜‰

As there are many ways of achieving this, I chose python

Pre-requisites:

First, we need to have a Twitter developer account, if you don't have.

1) Just navigate to Twitter Developer website 2) Just fill out the form with details about โ€˜what you want to do with their APIโ€™. You will be redirected to four forms, one form after another, complete them and agree to the developer terms and conditions and submit the application. This process may take like 10 minutes and you will get a verification email instantly once you submitted the form.

Alt Text

After getting approval from Twitter. Now we can create an app

1) Open this link and click on "create app"

2) Give your app a name. And you can't name an app which is already present.

Alt Text

3) Next, you will be redirected to API keys, tokens and click on "App Settings"

4) Now scroll down to the App permissions section and change the option from โ€œReadโ€ to โ€œRead and Writeโ€ and click on Save.

Alt Text

5) Now scroll to the top, and click on the option called โ€ Keys and Tokensโ€. Click on it and there you can see your Twitter API keys and Access Tokens by click on the โ€œview keysโ€ button and โ€œgenerateโ€ button respectively.

Alt Text

Here comes our logic part...

we should create two files,

  1. config.py
  2. counter.py

This config.py is responsible for creating an authenticated API using tweepy module and API Keys

config.py

import tweepy
import logging
from os import environ

logger = logging.getLogger()

def create_api():
    consumer_key = environ['CONSUMER_KEY']
    consumer_secret =  environ['CONSUMER_SECRET']
    access_token =  environ["ACCESS_TOKEN"]
    access_token_secret =environ["ACCESS_TOKEN_SECRET"]

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True,
                     wait_on_rate_limit_notify=True)
    try:
        api.verify_credentials()
    except Exception as e:
        logger.error('Error creating API', exc_info=True)
        raise e
    logger.info('API created')
    return api

Don't forget to add environmental variables when deploying

This counter.py runs every minute and checks the followers count if there is a change then it updates the name and followers count. We can use emoji's as well instead of numbers

counter.py

import tweepy
import logging
from config import create_api
import time

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()


def validate_follower_count(user):
    # update string split if you don't use this naming format for twitter profile:
    # 'insert_your_name|{emoji_follower_count(user)} Followers'
    current_follower_count = user.name.replace('|', ' ').split()
    return current_follower_count


def emoji_follower_count(user):
    emoji_numbers = {0: "0๏ธโƒฃ", 1: "1๏ธโƒฃ", 2: "2๏ธโƒฃ", 3: "3๏ธโƒฃ",
                     4: "4๏ธโƒฃ", 5: "5๏ธโƒฃ", 6: "6๏ธโƒฃ", 7: "7๏ธโƒฃ", 8: "8๏ธโƒฃ", 9: "9๏ธโƒฃ"}

    follower_count_list = [int(i) for i in str(user.followers_count)]

    emoji_followers = ''.join([emoji_numbers[k]
                               for k in follower_count_list if k in emoji_numbers.keys()])

    return emoji_followers


def main():
    api = create_api()

    while True:
        # change to your own twitter_handle
        user = api.get_user('aleti_sunil')


        if validate_follower_count(user) == emoji_follower_count(user):
            logger.info(
                f'You still have the same amount of followers, no update neccesary: {validate_follower_count(user)} -> {emoji_follower_count(user)}')
        else:
            logger.info(
                f'Your amount of followers has changed, updating twitter profile: {validate_follower_count(user)} -> {emoji_follower_count(user)}')
            # Updating your twitterprofile with your name including the amount of followers in emoji style
            api.update_profile(
                name=f'Sunil Aleti |  {emoji_follower_count(user)}')

        logger.info("Waiting to refresh..")
        time.sleep(60)


if __name__ == "__main__":
    main()

Now push the code to github and you can get files here

You can deploy this in AWS too but it is not my cup of tea. So, As we are deploying it to Heroku we need to add few more files

  • requirements.txt - As we are using tweepy module, we need to specify tweepy in requirements.txt
  • Procfile - This file specifies heroku to execute counter.py file
  • runtime.txt - In our case, we are using python, so mention python-3.6.9

Follow this video for further deployment in Heroku


If you like my content, please consider supporting me

Hope it's useful

A โค๏ธ would-be Awesome ๐Ÿ˜Š

No Comments Yet