基于python和树莓派的微博机器人(进阶篇:能够发图片微博)
先上代码
# -*- coding: utf-8 -*- #from weibopy.api import API from weibo import APIClient import sys,os,urllib,urllib2,cookielib,httplib import webbrowser import urlparse #模拟授权并且获取回调地址上的code,以获得acces token和token过期的UNIX时间 def get_code(): APP_KEY = 'xxxxxxxxxx' #你申请的APP_KEY APP_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx' #你申请的APP_SECRET #回调地址,可以用这个默认地址 CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html' AUTH_URL = 'https://api.weibo.com/oauth2/authorize' USERID = '[email protected]' #微博账号 PASSWD = 'xxxxxx' #微博密码 client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL) referer_url = client.get_authorize_url() print "referer url is : %s" % referer_url cookies = urllib2.HTTPCookieProcessor() opener = urllib2.build_opener(cookies) urllib2.install_opener(opener) postdata = {"client_id": APP_KEY, "redirect_uri": CALLBACK_URL, "userId": USERID, "passwd": PASSWD, "isLoginSina": "0", "action": "submit", "response_type": "code", } headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0", "Host": "api.weibo.com", "Referer": referer_url } req = urllib2.Request( url = AUTH_URL, data = urllib.urlencode(postdata), headers = headers ) try: resp = urllib2.urlopen(req) #print "callback url is : %s" % resp.geturl() code = resp.geturl()[-32:] #print "code is : %s" % resp.geturl()[-32:] except Exception, e: print e return code def begin(): APP_KEY = 'xxxxxxxx' # app key APP_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # app secret CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html' # callback url client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL) code = get_code() r = client.request_access_token(code) print r access_token = r.access_token # 新浪返回的token,类似abc123xyz456 expires_in = r.expires_in # token过期的UNIX时间 client.set_access_token(access_token, expires_in) #发普通微博 client.statuses.update.post(status=u'test') #发图片微博 f = open('C:/pic/test.jpg', 'rb') r = client.statuses.upload.post(status=u'测试OAuth 2.0带图片发微博', pic=f) f.close() # APIClient不会自动关闭文件,需要手动关闭 begin()
制作教程:首先你得有树莓派,还要去申请一个新浪微博的APP,还要再树莓派的linux下装好DS18B20的驱动。
本教程采用的是新浪微博的PYTHON SDK来实现这个功能。
申请了新浪的APP后,自然就会得到APP_KEY和APP_SECRET,填入1楼的代码中,再填入自己的微博账号密码,最后一点很重要,具体看图所示
之后就可以直接用SDK里的API去干你想干的事了,发图片,发微博还有别的balalbalala,具体可以参考,这是SDK作者的githubhttps://github.com/michaelliao/sinaweibopy/wiki/OAuth2-HOWTO
预告后面会上传一个用树莓派配合摄像头自动发照片的shell脚本,需要用到的内容:DS18B20的读取脚本,摄像头拍照的脚本,已经上面的发微博的脚本
先发一个预览给大家看看
共有 0 条评论