DEV Community

Cover image for Automating Twitter Followers Count
Sunil Aleti
Sunil Aleti

Posted on

Automating Twitter Followers Count

I've seen many people on Twitter where they append followers count to their name

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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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

Reference:
https://dev.to/radnerus/twitter-api-is-followers-count-mda

If you like my content, please consider supporting me

Buy Me A Coffee

Hope it's useful

A ❤️ would-be Awesome 😊

Top comments (0)