码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2016-07-13 22:53:35      阅读:455      评论:0      收藏:0      [点我收藏+]

标签:

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

 

参考链接:

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

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

说明:

  天气信息来自于百度地图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

git clone https://github.com/JetLua/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

def get_weather(city):
    api_key="you api key"
    weather_url="http://api.map.baidu.com/telematics/v3/weather?location="+city+"&output=json&ak="+api_key
    
    res = urllib.request.urlopen(weather_url)
    json_data = res.read().decode(utf-8)
    #print(json_data)
    json_data = json.loads(json_data)
    #get json data
    #check result status
    status = json_data[status]
    
    if status==success:
        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(~,)
        return 北京,今天是{},{} {},温度为{},PM2.5是{}..format(date,weather,wind,temperature,pm25)
    else:
        return 获取百度API失败~

def get_today():
    api_url = "http://www.ipip5.com/today/api.php?type=json"

    res = urllib.request.urlopen(api_url)
    json_data = res.read().decode(utf-8)
    #print(json_data)
    if json_data==‘‘:
        return 获取历史上的今天失败~
    json_data = json.loads(json_data)

    today = json_data[today]
    year = json_data[result][0][year]
    title = json_data[result][0][title]

    return {}年{}:{}.format(year,today,title)

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

qqUser=qq user
qqPass=qq pass
wbUser=weibo user
wbPass=weibo pass

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)
qq.feed(s)

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 = rhttps://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 = rhttp://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℃"
        }]
    }]
}

  历史上的今天返回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: "水利水电工程专家潘家铮逝世"
    }]
}

 

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

标签:

原文地址:http://www.cnblogs.com/tianzhenyun/p/5667739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!