Skip to content

Instantly share code, notes, and snippets.

@mine260309
Last active September 13, 2018 09:24
Show Gist options
  • Save mine260309/771512fc912d283496d9 to your computer and use it in GitHub Desktop.
Save mine260309/771512fc912d283496d9 to your computer and use it in GitHub Desktop.
Script to get Zhangjian, Shanghai's AQI, take a picture and tweet the status
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import os
import re
import requests
from datetime import datetime
from twython import Twython
CONSUMER_KEY = 'YOUR-CONSUMER-KEY'
CONSUMER_SECRET = 'YOUR-CONSUMER-SECRET'
ACCESS_KEY = 'YOUR-ACCESS-KEY'
ACCESS_SECRET = 'YOUR-ACCESS-SECRET'
WEATHER_API_ID = 'YOUR-OPENWEATHERMAP_API_ID'
useragent = ('Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36')
headers = {
'User-Agent': useragent
}
def get_aqi():
city = 'zhangjiang'
city_url = 'http://aqicn.org/city/shanghai/pudongzhangjiang/'
try:
content = requests.get(city_url, headers=headers).content.decode('utf-8')
pattern = ' overall air quality index is (\d+)'
results = re.findall(pattern, content)
if results:
return results[0]
except Exception as e:
raise e
def get_weather():
import json
payload = {'id': '1793105',
'APPID': WEATHER_API_ID,
'units': 'metric'}
url = 'https://api.openweathermap.org/data/2.5/weather'
try:
s = requests.get(url, params=payload).content.decode('utf-8')
except Exception as e:
raise e
d = json.loads(s)
return d['weather'][0]['main'].lower()
def capture_image(aqi, weather):
import subprocess
# Image name
image_file = '%s/imgs/image_%s_aqi_%s_%s.jpg' %( \
os.path.dirname(os.path.realpath(__file__)), \
datetime.now().strftime("%Y-%m-%d_%H"),
aqi,
weather)
title = u'浦东金色城市 AQI: %s %s @PiPudongAir' %(aqi, weather)
# Call fswebcam to capture the image
cmd = ['fswebcam', '-r', '640x480', '-S', '20', '--title',
title, image_file]
ret = subprocess.call(cmd)
if ret != 0:
raise os.error('Failed to capture image %s' % (image_file))
return image_file
if __name__ == '__main__':
aqi = get_aqi()
weather = get_weather()
imagefile = capture_image(aqi, weather)
tweet = u'浦东金色城市空气指数和照片\nAQI: %s\nWeather: %s\n%s\n#PudongAir' \
% (aqi, weather, datetime.now().strftime('%Y-%m-%d %H:%M'))
api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
image = open(imagefile, 'rb')
api.update_status_with_media(media=image, status=tweet)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment