Automating Twitter Followers Count
Tags: showdev, python, tutorial
Published: 2020-10-16 10:39:26

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😉
<a href="https://twitter.com/aleti_sunil" target="_blank">
  <img src="https://dev-to-uploads.s3.amazonaws.com/i/qd69pzb1wak64x86xu5l.PNG" />

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

<b>Pre-requisites:</b>

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

<b>1) </b>Just navigate to [Twitter Developer website](https://developer.twitter.com/en/apply-for-access)
<b>2) </b>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](https://dev-to-uploads.s3.amazonaws.com/i/sj0h0s810wga0ov1439q.PNG)

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

<b>1) </b>Open this [link](https://developer.twitter.com/en/portal/projects-and-apps) and click on "create app"

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/agft9om1foaemjvxfcw4.PNG)

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

<b>4) </b>Now scroll down to the App permissions section and change the option from “Read” to “Read and Write” and click on Save.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/te0oemuh0ozprcggwdde.PNG)

<b>5) </b>Now scroll to the top, and click on the option called <b>” Keys and Tokens”</b>. Click on it and there you can see your Twitter API keys and Access Tokens by click on the <b>“view keys”</b> button and <b>“generate”</b> button respectively.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jj18bv9lyddew6rzpudd.png)

Here comes our logic part...

we should create two files,
<ol>
<li>config.py</li>
<li>counter.py</li>
</ol>

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

<h3>config.py</h3>
```python
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 <b>counter.py</b> 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

<h3>counter.py</h3>
```python
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 <a href="https://github.com/aletisunil/TwitterFollowerCounter">here</a>
{% github aletisunil/TwitterFollowerCounter no-readme %}

You can deploy this in AWS too but it is not my cup of tea.
So, As we are deploying it to <a href="heroku.com">Heroku</a>
we need to add few more files
<ul>
<li><b>requirements.txt</b> - As we are using tweepy module, we need to specify tweepy in requirements.txt</li>
<li><b>Procfile</b> - This file specifies heroku to execute counter.py file</li>
<li><b>runtime.txt</b> - In our case, we are using python, so mention python-3.6.9</li>
</ul>

<b>Follow this video for further deployment in Heroku</b>

{% youtube PUA0fyraRmY %}


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

<b>If you like my content, please consider supporting me</b><br>
<a href="https://www.buymeacoffee.com/sunilaleti" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-black.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a><br>


Hope it's useful

A ❤️ would-be Awesome 😊