Creating a Twitter Bot to Tweet Solar StatsTechnology
For the past two years I have been using an EmonPi to log my homes energy usage. It has a great interface to show all the stats but if I'm away I don't want to have to VPN into my home network just to see what's going on.
So following in the footsteps of @Edent who has had his panels tweeting stats and photos I wanted see if I could create something similar and learn a bit about Twitter API's on the way.
Twitter + Python
I thought the Twitter part would be the hardest but it turns out getting a Python script to tweet something is actually super easy thanks to the module Tweepy. All you need is to generate some Twitter tokens and install the Python module and your all set.
Hello World! #myfirsttweet
— Solar Panel Bot (@z7ev3n_solar) 30 June 2016
@z7ev3n_solar's first ever tweet
The EmonPi runs the open-source web-app EmonCMS which has an API built in so grabbing data was no problem. It can give return all the readings between a given time frame in JSON however the time it uses is measured in UTC milliseconds and I'm working in GMT+1 so this took a little while to get used to and gave me a little insight into why this quote exists.
Never ever deal with timezones if you can help it.
-- Tom Scott
Using a days worth of data I could calculate cost, peak wattage and other stats which was good but I also wanted some graphics. I really like the existing EmonCMS solar stats page so I thought why can't I just change that a little bit and put a screenshot of it in my tweet.
So that's what I did, I created a HTML template of how I wanted it to look then set about implementing the Flot for some fancy graphs of the solar power generated. The script would then use the template to create a HTML page containing all the days values inside.
All I had to do now was render the HTML page so it could be saved as an image for Twitter. The tool webkit2png came in very handy and after a little tweaking to the design the script was done.
The First Useful Tweet
— Solar Panel Bot (@z7ev3n_solar) 1 July 2016
Finally I setup the code on the EmonPi itself so it could run without me, installing a few packages and a crontab entry was all that was needed to get it to send a tweet every evening.
The full code and basic documentation is available at github.com/z7ev3n/solar_bot