您的位置:首页 > 编程语言 > ASP

raspberry pi 自动发布天气信息到QQ空间/微博

2016-07-13 17:38 726 查看

raspberry pi 自动发布天气信息到QQ空间/微博 (2017-03-20更新)

参考链接:

  https://aoaoao.me/951.html/comment-page-1

  http://www.ipip5.com/today/api.php?type=json

  http://www.eoeandroid.com/thread-331843-1-1.html

说明:

  天气信息来自于百度地图API,历史上的今天来自于网络API(见上).

准备工作:

  安装python(没有的,自行下载安装)

  安装requests:

git clone git://github.com/kennethreitz/requests.git
cd requests
python3 setup.py install


  安装python-rsa

git clone https://github.com/sybrenstuvel/python-rsa.git cd python-rsa
python3 setup.py install


  安装qqlib(此库已经无法发表说说:2017-03-20更新,请安装下面的qqlib)

git clone https://github.com/JetLua/qqlib.git cd qqlib
python3 setup.py install


安装最新qqlib

git clone https://github.com/gera2ld/qqlib.git cd qqlib
python3 setup.py install


主要脚本:

  main.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import urllib.request
import sys
import json
import time
#import qqlib
from qqlib import qzone
import random
import gzip
import zlib
import re

def get_weather(city):
reg = r'[\u4E00-\u9FA5 ]'
#api_key="xxxx"
#weather_url="http://api.map.baidu.com/telematics/v3/weather?location="+city+"&output=json&ak="+api_key
#print(weather_url)
weather_url = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
request=urllib.request.Request(weather_url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36'})
try:
res = urllib.request.urlopen(request)
except urllib.error.HTTPError as e:
print(e.getcode())
print(e.reason)
print(e.geturl())
print('-----------------')
print(e.info())
print(e.read())
return 'get weather api data error....'
data = res.read()
if(('Content-Encoding' in res.info()) and ( res.info()['Content-Encoding'] == 'gzip')):
#data=zlib.decompress(data, 16+zlib.MAX_WBITS)
data = gzip.decompress(data)
data = str(data, 'utf-8')
#json_data = res.read().decode('utf-8')
#print(json_data)
json_data = json.loads(data)
#get json data
#check result status
status = json_data['status']

if(status == 1000):
'''
results=json_data['results'][0]
pm25=results['pm25']
weather_data=results['weather_data']
date=weather_data[0]['date']
weather=weather_data[0]['weather']
wind=weather_data[0]['wind']
temperature=weather_data[0]['temperature'].replace('~','到')
'''
wdata = json_data['data']
city = wdata['city']
aqi = int(wdata['aqi'])
temperature = wdata['wendu']
forecast = wdata['forecast'][0]
date = forecast['date']
weather = forecast['type']
wind = forecast['fengli']
direction = forecast['fengxiang']
high = re.sub(reg,'',forecast['high'])
low = re.sub(reg,'',forecast['low'])
level = ''
if(aqi <= 50 and aqi > 0):
level = '优秀'
elif(aqi <= 100 and aqi > 50):
level = '良好'
elif(aqi <= 150 and aqi > 100):
level = '一般'
elif(aqi <= 200 and aqi > 150):
level = '很差'
else:
level = '很差'
return '{},今天是{} {}, 空气质量:{}{},当前温度{}[{} ~ {} ],{}{}.'.format(city,date,weather,aqi,level,temperature,low,high,direction,wind)
else:
return '获取百度API失败~'

def get_today():
api_url = "http://www.ipip5.com/today/api.php?type=json"
#api_url='https://brisk.eu.org/api/today-history.php'
request=urllib.request.Request(api_url, headers={'User-Agent': 'Mozilla/5.0'})
res = urllib.request.urlopen(request)
json_data = res.read().decode('utf-8')
#print(json_data)
if json_data=='':
return '获取历史上的今天失败~'
json_data = json.loads(json_data)

total = len(json_data['result'])
num = random.randint(0,total)
today = json_data['today']
year = json_data['result'][num]['year']
title = json_data['result'][num]['title']

return '{}年{} {}'.format(year,today,title)
'''
total=len(json_data['res'])
num=random.randint(0,total)
return json_data['res'][num]
'''

weather = get_weather('beijing')
today = get_today()
text = '[天气自动播报] {}\n[历史上的今天] {}\n(此消息来自我家树莓派自动发送)'.format(weather,today)
#print(text)

qqUser='qqUser'
qqPass='qqPass'
wbUser='wbUser'
wbPass='wbPass'

if os.path.exists('/home/pi/autopublish/data.txt'):
with open('/home/pi/autopublish/data.txt','wt') as f:
f.write(text)
f.close()
print(text)
else:
print('file data.txt not exists')

#qq
#qq = qqlib.QQ(qqUser,qqPass)
#2017-03-20更新
qq = qzone.QZone(qqUser, qqPass)
qq.login()
qq.feed(text)

try:
os.system('python3 /home/pi/autopublish/weibo.py {} {}'.format(wbUser,wbPass))
except Exception as e:
print('Exception',e)


  weibo.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
import requests
import json
import time
import os

class weibo:
def __init__(self, username, password):
self.__username = username
self.__password = password
try:
self.cookies = self.__login__().cookies
self.status = True
except:
self.cookies = None
self.status = False

def __login__(self):
url = r'https://passport.weibo.cn/sso/login'
header = {
'Host':'passport.weibo.cn',
'User-Agent':'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A403 Safari/8536.25',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding':'gzip, deflate',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
'Pragma':'no-cache',
'Cache-Control':'no-cache',
'Referer':'https://passport.weibo.cn/signin/login',
'Connection':'keep-alive'}
post_data = {
'username':'%s' % self.__username,
'password':'%s' % self.__password,
'savestate':'1',
'ec':'0',
'pagerefer':'',
'entry':'mweibo',
'loginfrom':'',
'client_id':'',
'code':'',
'qq':'',
'hff':'',
'hfp':''}
try:
response = requests.post(url, data = post_data, headers = header)
#print u'success\nuid:'+json.loads(response.text)['data']['uid']
return response
except:
#print u'failed'
return None

def update(self, text):
url = r'http://m.weibo.cn/mblogDeal/addAMblog'

header = {
'Host':'m.weibo.cn',
'User-Agent':'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A403 Safari/8536.25',
'Accept':'application/json, text/javascript, */*; q=0.01',
'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding':'gzip, deflate',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With':'XMLHttpRequest',
'Referer':'http://m.weibo.cn/mblog',
'Connection':'keep-alive'
}

post_data = {
'content':text
}
try:
response = requests.post(url = url, data = post_data, headers = header, cookies = self.cookies)
#print json.loads(response.text)['msg']
return response
except:
try:
time.sleep(10)
try:
self.cookies = self.__login__().cookies
except:
self.cookies = None
return None
response = requests.post(url = url, data = post_data, headers = header, cookies = self.cookies)
#print json.loads(response.text)['msg']
return response
except:
#print u'send failed'
return None

if __name__ == '__main__':
username = sys.argv[1]
password = sys.argv[2]
w = weibo(username, password)
file_r = open('/home/pi/autopublish/data.txt')
data_old = file_r.read()
file_r.close( )
w.update(data_old)


附录:

  百度天气API返回JSON示例:

{
error: 0,
status: "success",
date: "2016-07-13",
results: [{
currentCity: "北京",
pm25: "54",
index: [{
title: "穿衣",
zs: "炎热",
tipt: "穿衣指数",
des: "天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。"
},
{
title: "洗车",
zs: "较适宜",
tipt: "洗车指数",
des: "较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。"
},
{
title: "旅游",
zs: "一般",
tipt: "旅游指数",
des: "天气较好,同时又有微风伴您一路同行,但是比较热,外出旅游请注意防晒,并注意防暑降温。"
},
{
title: "感冒",
zs: "少发",
tipt: "感冒指数",
des: "各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。"
},
{
title: "运动",
zs: "较适宜",
tipt: "运动指数",
des: "天气较好,户外运动请注意防晒。推荐您进行室内运动。"
},
{
title: "紫外线强度",
zs: "强",
tipt: "紫外线强度指数",
des: "紫外线辐射强,建议涂擦SPF20左右、PA++的防晒护肤品。避免在10点至14点暴露于日光下。"
}],
weather_data: [{
date: "周三 07月13日 (实时:35℃)",
dayPictureUrl: "http://api.map.baidu.com/images/weather/day/qing.png",
nightPictureUrl: "http://api.map.baidu.com/images/weather/night/duoyun.png",
weather: "晴转多云",
wind: "微风",
temperature: "35 ~ 23℃"
},
{
date: "周四",
dayPictureUrl: "http://api.map.baidu.com/images/weather/day/zhenyu.png",
nightPictureUrl: "http://api.map.baidu.com/images/weather/night/yin.png",
weather: "阵雨转阴",
wind: "微风",
temperature: "33 ~ 23℃"
},
{
date: "周五",
dayPictureUrl: "http://api.map.baidu.com/images/weather/day/yin.png",
nightPictureUrl: "http://api.map.baidu.com/images/weather/night/yin.png",
weather: "阴",
wind: "微风",
temperature: "31 ~ 22℃"
},
{
date: "周六",
dayPictureUrl: "http://api.map.baidu.com/images/weather/day/duoyun.png",
nightPictureUrl: "http://api.map.baidu.com/images/weather/night/duoyun.png",
weather: "多云",
wind: "微风",
temperature: "32 ~ 22℃"
}]
}]
}


  中华万年历API数据

{
"desc": "OK",
"status": 1000,
"data": {
"wendu": "33",
"ganmao": "各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。",
"forecast": [
{
"fengxiang": "西南风",
"fengli": "3-4级",
"high": "高温 39℃",
"type": "晴",
"low": "低温 29℃",
"date": "26日星期二"
},
{
"fengxiang": "西南风",
"fengli": "3-4级",
"high": "高温 37℃",
"type": "多云",
"low": "低温 29℃",
"date": "27日星期三"
},
{
"fengxiang": "西南风",
"fengli": "3-4级",
"high": "高温 37℃",
"type": "晴",
"low": "低温 28℃",
"date": "28日星期四"
},
{
"fengxiang": "西南风",
"fengli": "3-4级",
"high": "高温 37℃",
"type": "多云",
"low": "低温 28℃",
"date": "29日星期五"
},
{
"fengxiang": "东南风",
"fengli": "微风级",
"high": "高温 37℃",
"type": "多云",
"low": "低温 27℃",
"date": "30日星期六"
}
],
"yesterday": {
"fl": "3-4级",
"fx": "南风",
"high": "高温 38℃",
"type": "晴",
"low": "低温 29℃",
"date": "25日星期一"
},
"aqi": "93",
"city": "南京"
}
}


  历史上的今天返回JSON示例1(www.ipip5.com/today/api.php?type=json):

{
today: "07月13日",
result: [{
year: "1518",
title: "中国明代医药学家李时珍出生"
},
{
year: "1793",
title: "雅各宾派主要领导人之一马拉逝世"
},
{
year: "1900",
title: "八国联军攻陷天津"
},
{
year: "1908",
title: "台湾画家李石樵出生于台北县新庄镇,一九九五年病逝于美国。"
},
{
year: "1930",
title: "第一届世界杯在乌拉圭开幕"
},
{
year: "1942",
title: "美国影星哈里森·福特出生"
},
{
year: "1944",
title: "魔方之父厄尔诺·鲁比克出生."
},
{
year: "1953",
title: "抗美援朝金城战役打响"
},
{
year: "1954",
title: "玻璃纸发明人布兰德伯格逝世"
},
{
year: "1954",
title: "墨西哥女画家弗里达·卡罗逝世"
},
{
year: "1956",
title: "中国第一批解放牌汽车试制成功"
},
{
year: "1961",
title: "奥地利作曲家勋伯格去世"
},
{
year: "1983",
title: "中国田径运动员刘翔出生"
},
{
year: "2001",
title: "北京申办2008年奥林匹克运动会成功"
},
{
year: "2012",
title: "水利水电工程专家潘家铮逝世"
}]
}


  历史上的今天返回JSON示例1(https://brisk.eu.org/api/today-history.php) [2016-8-15update ,this api return empty]:

{
res: ["155年07月18日 曹操诞辰",
"1139年07月18日 南宋名将吴玠逝世",
"1635年07月18日 英格兰物理学家胡克出生",
"1811年07月18日 英国作家萨克雷诞辰",
"1817年07月18日 英国作家简·奥斯汀逝世",
"1853年07月18日 荷兰理论物理学家洛伦兹诞生",
"1857年07月18日 “清末怪杰”国学大师辜鸿铭出生",
"1872年07月18日 墨西哥总统贝尼托·华雷斯逝世",
"1883年07月18日 俄国布尔什维克党早期活动家加米涅夫诞辰",
"1899年07月18日 居里夫妇发现“钋”",
"1909年07月18日 美国内华达州雷诺市成了离婚城",
"1918年07月18日 南非总统曼德拉诞辰",
"1925年07月18日 希特勒《我的奋斗》出版发行",
"1927年07月18日 宋庆龄斥责汪精卫、蒋介石叛变革命",
"1933年07月18日 蒋介石开办庐山军官训练团",
"1936年07月18日 西班牙内战爆发",
"1937年07月18日 探险家埃尔哈特在环球飞行中失踪",
"1942年07月18日 史迪威提出“反攻缅甸计划”",
"1942年07月18日 国际米兰主席法切蒂出生",
"1942年07月18日 德国梅塞施密特喷气战斗机首次试飞成功",
"1947年07月18日 英国拦截逃离德国的犹太人的轮船",
"1955年07月18日 第一座迪斯尼乐园正式向公众开放",
"1955年07月18日 国务院通过决议撤销热河省和西康省",
"1956年07月18日 中国政府宽释第二批日本战犯",
"1965年07月18日 拉丁美洲议会成立",
"1969年07月18日 香港废止“华律治华人”纳妾制度",
"1969年07月18日 因足球赛而发生的战争停火",
"1972年07月18日 埃及驱逐苏联顾问",
"1980年07月18日 《人民日报》发文章总结“大寨经验”的教训",
"1985年07月18日 “尤里卡”计划诞生",
"1985年07月18日 全国劳动模范马恒昌逝世",
"1986年07月18日 尼日利亚第一位华侨南扬被任命为酋长",
"1988年07月18日 伊朗接受联合国安理会598号停火决议",
"1991年07月18日 受贿贪污犯管志诚被判处死刑",
"1993年07月18日 日本执政38年的自民党下野",
"1998年07月18日 长征火箭发射欧洲制造“鑫诺1号”通信卫星",
"1998年07月18日 中国联通打破中国电信垄断地位",
"1998年07月18日 曼德拉80寿辰喜结良缘",
"1998年07月18日 专家推算黄河2020年下游全年断流",
"2005年07月18日 美国为印度提供民用核能技术",
"2006年07月18日 中国新闻奖首次将网络新闻作品纳入评选",
"2007年07月18日 温家宝会见土库曼斯坦总统",
"2014年07月18日 台风“威马逊”登陆琼粤桂"]
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: