I decided to make use of the self quarantine, work from home time to start learning some skills on the side. I started looking at Python (again) and did a tutorial to relearn the basics of the Python. I am one of those people who is always in tutorial purgatory, who often sees tutorials on various things and end up forgetting about it completely due to not doing any hands on practice. Half way through the tutorial, I realized that I am manually posting a tweet thread to Twitter, which could be automated easily.
The tweet thread is simple, a daily reminder of the number of days since I wore pants. Here is draft version of the code if someone wants to skip reading this blog.
What I love most about Python ecosystem is that there is always some library written by someone for most of my common needs. I found that tweepy was the easiest way to tweet using Python.
I registered a twitter developer account and found this site to guide me in creating the app for interacting with Twitter. This site also lists out steps to create similar apps for other sites such as Facebook, LinkedIn.
Now coming back to the Python script, it uses 2 text files for now (remember that I am still half way doing the tutorial :))
- First for storing the counter of number of days since I wore my pants.
- Second for storing the tweet id that is being posted. You will need to have the id of the tweet if you want to reply to it. I wanted to maintain the tweet chain that I already had and post the new tweets as a reply to last tweet. I decided to store id of the tweet instead of doing a get request every time to Twitter to find my last tweet. This made sense to me as the design decision.
All of the logic is split into individual functions so that I can rewrite those as I learn more about Python. Most of the code is self explanatory. There are functions for reading from file, writing string to file, reply to a existing tweet and a function to increment to days counter.
The script when executed works as below,
- Reads the counter from the text file.
- Increments the counter and writes it back to the same file.
- Message is formed using the days count.
- Last tweet id is read from another file.
- Tweet is posted and id of the new tweet is saved back to the file for next tweet.
The script still needs rework to move the Twitter app details outside of the script, find a better way to store counter and tweet id and do some basic error handling. I am hoping to do this as I complete pending tutorial.
Bonus: I automated the execution of this using Crontab. This site helps you create a cron schedule expression if you have problem understanding it's format. And, if you don't know how to create crontab, then see this video
Top comments (0)