How we Automated our 100DaysOfCode Daily Tweet

Bob, Wed 05 April 2017, Tools

100days, automation, logging, pytz, tools, tweepy, twitter

In this article I show you a way to automatically tweet your #100DaysOfCode Challenge progress. This saves you some extra time to focus on the coding. Isn't that all what matters?

This is day 007 of our 100 Days of Code challenge. You can follow along by forking our repo.

Getting ready

You need pytz, tweepy and requests. You can pip install -r requirements.txt if you cloned our repo (after cd-ing in 007). We recommend using virtualenv to isolate environments.

As explained in a previous article you need to get a Consumer Key/Secret and Access Token (Secret) from Twitter. I added those to my .bashrc which I load in via os.environ in config.py. There I also started a logging handler I use to log outgoing tweets and any exceptions that may occur.

The main script

See here and below what I learned:

Deployment

On my server I had to do some magic to get it all working: source .bashrc to load in the ENV vars, export PYTHONPATH, and specify the full path to python3. As explained here: "Cron knows nothing about your shell; it is started by the system, so it has a minimal environment."

$ crontab -l
...
34 14 * * * source $HOME/.bashrc && export PYTHONPATH=$HOME/bin/python3/lib/python3.5/site-packages && cd $HOME/code/100days/007 && $HOME/bin/python3/bin/python3.5 100day_autotweet.py

Result

What a coincidence: as I write this our today's progress tweet just went out :)

my automated tweet

Logging

The cool thing about the logging module is that you get the external packages' logging for free. When I look at the log I see a lot more than my script's logging:

$ vi 100day_autotweet.log
...
...
14:34:02 tweepy.binder INFO     PARAMS: {'status': b'#100DaysOfCode - Day 007: script to automatically tweet 100DayOfCode progress tweet https://github.com/pybites/100DaysOfCode/tree/master/007 #Python'}
...
many more log entries ...
...
14:34:02 requests.packages.urllib3.connectionpool DEBUG    https://api.twitter.com:443 "POST /1.1/statuses/update.json?status=%23100DaysOfCode+-+Day+007%3A+script+to+automatically+tweet+100DayOfCode+progress+tweet+https%3A%2F%2Fgithub.com%2Fpybites%2F100DaysOfCode%2Ftree%2Fmaster%2F007+%23Python HTTP/1.1" 200 2693
14:34:02 root         INFO     Posted to Twitter ==> my message

Of course you can mute these by raising the log level (INFO or higher) in logging.basicConfig (config.py). See the docs for more info.


I hope this taught you a bite of Python and it inspired you to automate your 100DaysOfCode and/or other tweets. Let us know how it goes ... Happy coding!

Keep Calm and Code in Python!

-- Bob