Post by impactoz on Aug 22, 2019 5:12:51 GMT -8
So I wrote this little ditty below so I can send out a daily weather tweet on twitter... The following is my test code - that you should be able to integrate into your own system if you wanted...
The steps go something like;
- Register yourself on Twitter
- Apply for a developers account
- Receive the 4 codes required to be able to set up a bot
- Install Twitter API on your raspberry PI
- Write some simple code like this;
The XXXXXXXXXXX is what you need to fill in with the 'secret' twitter codes you get from registering a bot.. You have to write reasons why and what your using it for - but just say your giving weather info out to the community - fill up the required lengths, and the codes are sent to you straight away - its not vetted by a human... its just really comments in case your doing something naughty and someone complains...
I have this in a cron job to run at 7:30am each morning - I have changed the Date(NOW())) to be a calculation for the previous day, since I am running it the following day of the report...
Originally when I started this I was going to run it just before midnight - didn't really care if I missed the last 5 minutes of the official day - shouldn't change the report too much... But then I thought - why do I want to hear my phone go beep at that hour every night.... Im not going to be reading it... Nah - far better just to run it in the morning... Im normally up before 730am, so that's the time chose - more likely to look at the tweet - but its fully your decision...
The code above would work for you - except it references a picture you will not currently have - file = open('static/sunset.jpg', 'rb')
I have another daily job that calculates each day based on location when sunset occurs, and this job just takes another picture from the camera. So the tweet sends out daily information along with the picture of sunset that day... Again I could have made this anytime - I just decided sunset would be best for my personal choice... I use tools to resize it down to Twitter size, add a header - was going to super impose the high / low on it, but decided against it. If your interested in that I can make that a different post.
So change it back to SkyCamera.jpg which you should be creating every few minutes, or just remove the media file altogether...
I just didn't like the idea of blynk… yet another app on the phone that really served no purpose... and ummm… Im a cheapstake, don't like in app purchases to buy credits to do functionality.... and that's when I thought - I could just tweet the info...
The API is powerful and so is the concept of bots, I could write it to be interactive, where tweeting my account, it could reply with a report or details - but nah that's probably overkill...
I like to use information that I collect - and so far I am disappointed with Lightning Info - its put in the database and forgotten about - cant upload it to Weather Underground.... WeatherStem does not seem to show much info, and yeah it works probably OK with Blynk - but im not using it...
So tomorrows enhancement for me - Anytime there is a lightning detection, I will tweet that... So no matter wherever I am in the real world I will get a notification... Might ignore it... but at least its feedback !! And boy am I impressed with speed. Subsecond response on sending a tweet and receiving it on my phone...
Enjoy - Screen shot shows the tweet - ignore the picture, as its still all experimental !!! And Im likely to change the formatting still...
The steps go something like;
- Register yourself on Twitter
- Apply for a developers account
- Receive the 4 codes required to be able to set up a bot
- Install Twitter API on your raspberry PI
- Write some simple code like this;
import requests
import time
import picamera
import state
import hashlib
import traceback
import util
import datetime as dt
import MySQLdb as mdb
# Check for user imports
try:
import conflocal as config
except ImportError:
import config
from TwitterAPI import TwitterAPI
CONSUMER_KEY = 'XXXXXXXXXXXXXXXXXXXX'
CONSUMER_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
ACCESS_TOKEN_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXX'
ACCESS_TOKEN_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXX'
api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
file = open('static/sunset.jpg', 'rb')
data = file.read()
con = mdb.connect('localhost', 'root', config.MySQL_Password, 'SkyWeather');
query = "SELECT `outsideTemperature`, TIME_FORMAT(Time(CONVERT_TZ(TimeStamp,'+00:00','+10:00')),'%h:%i %p') FROM `WeatherData` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW()) and `outsideTemperature` in (SELECT Max(`outsideTemperature`) FROM `WeatherData` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW())) LIMIT 1"
cur = con.cursor()
cur.execute(query)
record = cur.fetchone()
msg = "Todays Weather Report\n"
msg = ""
msg += "High: %0.1fc at %1s\n" % (record[0], record[1])
query = "SELECT `outsideTemperature`, TIME_FORMAT(Time(CONVERT_TZ(TimeStamp,'+00:00','+10:00')),'%h:%i %p') As LocalTm FROM `WeatherData` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW()) and `outsideTemperature` in (SELECT Min(`outsideTemperature`) FROM `WeatherData` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW())) LIMIT 1"
cur = con.cursor()
cur.execute(query)
record = cur.fetchone()
msg += "Low: %0.1fc at %1s\n" % (record[0], record[1])
query = "SELECT MAX(`totalRain`) FROM `WeatherData` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW())"
cur = con.cursor()
cur.execute(query)
record = cur.fetchone()
if record[0] > 0:
msg += "Rainfall: %0.2fmm\n\n" % record[0]
else:
msg += "No Rain Today\n\n"
query = "SELECT `currentWindGust`, TIME_FORMAT(Time(CONVERT_TZ(TimeStamp,'+00:00','+10:00')),'%h:%i %p') FROM `WeatherData` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW()) and `currentWindGust` in (SELECT Max(`currentWindGust`) FROM `WeatherData` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW())) LIMIT 1"
cur = con.cursor()
cur.execute(query)
record = cur.fetchone()
if record[0] > 0:
msg += "Max Wind: %0.1fkmh At %1s\n\n" % (record[0], record[1])
else:
msg += "No Wind Gusts Today\n\n"
query = "SELECT `as3935LightningCount` FROM `WeatherData` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW()) and `as3935LightningCount` in (SELECT Max(`as3935LightningCount`) FROM `WeatherData` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW())) LIMIT 1"
cur = con.cursor()
cur.execute(query)
record = cur.fetchone()
if record[0] == 0:
msg += "No Lightning Today\n\n"
else:
msg += "%0.0f Lightning Strikes\n" % record[0]
query = "SELECT MIN(`as3935LastDistance`) FROM `WeatherData` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW()) AND `as3935LastDistance`> 0 LIMIT 1"
cur = con.cursor()
cur.execute(query)
record = cur.fetchone()
msg += "Range %0.1fkm To " % record[0]
query = "SELECT MAX(`as3935LastDistance`) FROM `WeatherData` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW()) AND `as3935LastDistance`> 0 LIMIT 1"
cur = con.cursor()
cur.execute(query)
record = cur.fetchone()
msg += "%0.1fkm\n" % record[0]
query = "SELECT DATE_FORMAT(CONVERT_TZ(Max(TimeStamp),'+00:00','+10:00'),'%a %d %b %Y'), TIME_FORMAT(Time(CONVERT_TZ(Max(TimeStamp),'+00:00','+10:00')),'%h:%i %p') FROM `WeatherData` where `as3935LightningCount` > 0 LIMIT 1"
cur = con.cursor()
cur.execute(query)
record = cur.fetchone()
if record[0] > 0:
msg += "Last Lightning On %0s %0s\n\n" % (record[0], record[1])
query = "SELECT `UVIndex`, TIME_FORMAT(Time(CONVERT_TZ(TimeStamp,'+00:00','+10:00')),'%h:%i %p') FROM `Sunlight` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW()) and `UVIndex` in (SELECT Max(`UVIndex`) FROM `Sunlight` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW())) LIMIT 1"
cur = con.cursor()
cur.execute(query)
record = cur.fetchone()
if record[0] < 3:
UVval = "Low"
elif record[0] >=3 and record[0] < 6:
UVval = "Moderate"
elif record[0] >=6 and record[0] < 8:
UVval = "High"
elif record[0] >=8 and record[0] < 11:
UVval = "Very High"
else:
UVval = "Extreme"
msg += "UV Index: %0.1f " % record[0]
msg += "(" + UVval + ") at "
msg += "%0s\n" % record[1]
query = "SELECT Avg(`UVIndex`) FROM `Sunlight` WHERE Date(CONVERT_TZ(TimeStamp,'+00:00','+10:00')) = Date(NOW()) And `UVIndex` > 0"
cur = con.cursor()
cur.execute(query)
record = cur.fetchone()
if record[0] < 3:
UVval = "Low"
elif record[0] >=3 and record[0] < 6:
UVval = "Moderate"
elif record[0] >=6 and record[0] < 8:
UVval = "High"
elif record[0] >=8 and record[0] < 11:
UVval = "Very High"
else:
UVval = "Extreme"
msg += "Avg UV Index: %0.1f " % record[0]
msg += "(" + UVval + ")"
print "***** Sending Daily Summary Tweet ******"
print msg
print "Length Msg: " , len(msg)
r = api.request('statuses/update_with_media', {'status': msg}, {'media[]':data})
if r.status_code == 200:
print "Status Code: 200 is good - it was sent"
else:
print "Error on Send: Code: " , r.status_code
The XXXXXXXXXXX is what you need to fill in with the 'secret' twitter codes you get from registering a bot.. You have to write reasons why and what your using it for - but just say your giving weather info out to the community - fill up the required lengths, and the codes are sent to you straight away - its not vetted by a human... its just really comments in case your doing something naughty and someone complains...
I have this in a cron job to run at 7:30am each morning - I have changed the Date(NOW())) to be a calculation for the previous day, since I am running it the following day of the report...
Originally when I started this I was going to run it just before midnight - didn't really care if I missed the last 5 minutes of the official day - shouldn't change the report too much... But then I thought - why do I want to hear my phone go beep at that hour every night.... Im not going to be reading it... Nah - far better just to run it in the morning... Im normally up before 730am, so that's the time chose - more likely to look at the tweet - but its fully your decision...
The code above would work for you - except it references a picture you will not currently have - file = open('static/sunset.jpg', 'rb')
I have another daily job that calculates each day based on location when sunset occurs, and this job just takes another picture from the camera. So the tweet sends out daily information along with the picture of sunset that day... Again I could have made this anytime - I just decided sunset would be best for my personal choice... I use tools to resize it down to Twitter size, add a header - was going to super impose the high / low on it, but decided against it. If your interested in that I can make that a different post.
So change it back to SkyCamera.jpg which you should be creating every few minutes, or just remove the media file altogether...
I just didn't like the idea of blynk… yet another app on the phone that really served no purpose... and ummm… Im a cheapstake, don't like in app purchases to buy credits to do functionality.... and that's when I thought - I could just tweet the info...
The API is powerful and so is the concept of bots, I could write it to be interactive, where tweeting my account, it could reply with a report or details - but nah that's probably overkill...
I like to use information that I collect - and so far I am disappointed with Lightning Info - its put in the database and forgotten about - cant upload it to Weather Underground.... WeatherStem does not seem to show much info, and yeah it works probably OK with Blynk - but im not using it...
So tomorrows enhancement for me - Anytime there is a lightning detection, I will tweet that... So no matter wherever I am in the real world I will get a notification... Might ignore it... but at least its feedback !! And boy am I impressed with speed. Subsecond response on sending a tweet and receiving it on my phone...
Enjoy - Screen shot shows the tweet - ignore the picture, as its still all experimental !!! And Im likely to change the formatting still...