Social Media Accounts Shouldn't Be Static! šš½
Inspired by other posts across the Internet
This Video Has 15,608,459 Views - YouTube
This Post Has 2,233 Views, 154 Reactions And 23 Comments - DEV
I decided to try to accomplish the same on Twitter with my username field and the number of followers I have.
The process is pretty straight forward, lets outline it
1. Connect to twitter API
2. Get my current number of followers
3. Update my username field
4. Repeat every 10 minutes
Now that weāve outlined the process lets breakdown the code and infrastructure
For this project I decided to use Python3. I really like using it for quick scripts over node.js because I donāt want to deal with asynchronous code; its nice to have code that runs one line, after the next, with no interruptions.
You will need Twitter API credentials for this project, if you donāt have them yet, youāll have to apply for them at https://developers.twitter.com.
To connect to the Twitter API Iāll be using Tweepy. Itās great, it works easily and has built in support for Twitter APIās rate limiting.
For hosting and scheduling I like to use Heroku. Heroku allows you to run your code and have an exposed web service, capable of handling web requests and serving up content. In this project we wonāt be handling any external request, nor serving up data, but we will still need to make sure our code plays well with Heroku, so weāll be sure to add a web server, in this case Flask easily fills the gap.
For our code to run on a schedule or every X minutes, we will enable a Heroku add-on for our project, Heroku Scheduler
which once configured will launch our script on our defined schedule.
Awesome, letās dive into the code!
import tweepy
from flask import Flask
First up we have our import
statements, these statements allow us to use functionality provided by 3rd party libraries.
The os
library gives us access to the underlying operating system and allows us to run commands directly on the host.
Tweepy
is going to enable us to connect and communicate with the Twitter API.
Flask
is a micro web framework enabling us to handle http requests and many other features, for this project weāre using it to satisfy heroic deployment needs.
Next up is authentication
# Authenticate to Twitter
auth = tweepy.OAuthHandler("consumer_key", "consumer_secret")
auth.set_access_token("token_key", "token_secret")
We need two sets of keys to authenticate, both can be found on the twitter developers page on your app, similar to the screenshot below.
Once youāve added those keys, the next step is connecting to the API server and getting some data.
# Create API object
api = tweepy.API(auth)
#get my user object
iam = api.me()
followers_count = iam.followers_count
The me()
method of the tweepy
object connects to the twitter API and pulls down the current authenticated users user data.
The user data object thats returned to us can accessed by using the dot .
operator, in this case we want the followers_count
attribute.
If you donāt know the attributes of an object you can use these builtins:
`dir(object)`
`vars(object)`
`__dict(object)__`
Combine that with PrettyPrint for some legibility:
BONUS CODE SNIPPET
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(vars(object))
Now that weāre done with that little detour, letās get back on track.
The next part of the code should update our username
api.update_profile(name=āJason Alvarez is {} new friends away from 10k".format(10000 - int(followers_count)))
Tweepy provides us a function called update_profile
which will update our profile depending on the parameters supplied to it. In this case weāre passing the name
parameter and giving it the following string
āJason Alvarez is {} new friends away from 10kā.format(10000 - int(followers_count)))
Rather than insert just a number, I decided to use the space as a countdown to a specific target.
Format takes a string with placeholders {}
and inserts the values supplied (value1, value2ā¦)
string.format(value1, value2ā¦)
This same technique can be applied to any editable field in a profile and any data that the API wonāt reject for input; please refer to Docs ā Twitter Developers for more details on valid and invalid characters.
The last segment of code is needed for the script to gracefully run on Herokuās infrastructure. While not specific for this project, letās go over what it does and what itās not doing.
app = Flask(__name__)
app.run()
Flask as mentioned above is a micro web framework, itās used normally to create servers that handle http(s) requests and other really neat things. In this case we need to start a server so that Heroku knows our deployment was successful.
One of the big uses for Flask, is to create your own API Microservices, where you can define your own HTTP routes, a feature we are not using in this case, and is outside the scope of this writeup but I highly suggest you look into it!
OKAY THE CODE IS DONE!
Great! Weāve finished writing our script and that means weāre all done and can deploy, right? ALMOST!
To deploy to Heroku successfully we need two more files:
requirements.txt
Procfile
requirements.txt
outlines the libraries needed for our code to run successfully and this isnāt something you need to create manually.
To generate your requirements.txt
run this command in your project directory pip3 freeze > requirements.txt
From Herokuās documentation
Heroku apps include a Procfile that specifies the commands that are executed by the app on startup.
Ourās is going to be real simple and just launch that web server we declared in our script.
Edit your Procfile
so it has the following contents
web: FLASK_APP=update_username.py flask run --port $PORT --host 0.0.0.0
$PORT
will be supplied to us by the operating system shell environment, and will be random, so donāt try and set anything here.
Great, if youāve made it this far your directory should look like the following
.
āāā Procfile
āāā requirements.txt
āāā update_username.py
NOW WE CAN FINALLY DEPLOY!
Create a new project on heroku.com and follow the onscreen instructions, itās a lot like setting up a GitHub repo. * Create a project * init * add * push (Follow their instructions for more details)
If your push and deploy were successful, you should see something like the following in your terminal
app[scheduler.5678]: * Running on http://0.0.0.0:48547/ (Press CTRL+C to quit)
heroku[scheduler.5678]: State changed from starting to up
heroku[scheduler.5678]: Cycling
heroku[scheduler.5678]: State changed from up to complete
At this point your Twitter user name should now be updated with the string you used in the script. In my use case I want my user name to be pretty in sync with the number of followers I have, so letās set it up to run on a schedule.
To accomplish this weāre going to use a Heroku project add-on called āHeroku Schedulerā, itās free and shouldnāt bump up the cost of your dyno, add it to the project, then click it to configure the jobs.
To stay as in sync as I can I chose a āEvery 10 minutesā job and for the run command, I used the same content thatās in the Procfile
-
FLASK_APP=update_username_num_followers.py flask run āport $PORT āhost 0.0.0.0
Save the job and youāre all done.
Letās go over what weāve accomplished.
1. We have a script that will update our Twitter username
2. It communicates with Twitter API for data
3. Our code project is deployed on a managed service
Thats not bad for a little fun script!
Enjoyed the post? Let me know! šš¦š