您的位置:首页 > 编程语言 > Python开发

用python自动发微博

2016-06-04 04:38 399 查看
……刚刚全部写完了点发布……结果什么都没保存……内心好忧伤。

终极目标是用raspberry pi + camera 捕捉画面,处理图像识别图中有我家主子(猫), 然后自动capture图像,发微博。raspberry pi明天才能送到,所以昨天晚上倒腾了下发微博的部分,发现还是很方便哒。 而且其实我之前从来没碰过python……所以……还是很好上手的。

啊还是放个自己的github的链接吧:https://github.com/bennygato/catcam

(此处要有主子照片~)



1.首先需要申请到一个应用 才有 app key 和 app
scret

网址是:http://open.weibo.com/development/mobile

然后点击 应用开发 -> 移动应用 然后根据个人信息填写,之后会收到邮件 里边有app key, app secret  





非常重要!去应用信息-高级信息里面填写回调页 这是什么我也不知道!但是照着填!我填的是 https://api.weibo.com/oauth2/default.html 这个需要和之后的python code里面的 callback url一致!!!



2. 安装 新浪微博sdk

sudo apt-get install python-pip

sudo pip install sinaweibopy

mac os 的话是:

sudo easy_install pip
sudo pip install sinaweibopy

3. Python Code

'''
checkout http://blog.csdn.net/bennygato/article/details/51582715 for
more instructions
'''
#encoding=utf-8

import time
from weibo import APIClient

def get_access_token(app_key, app_secret, callback_url):
client = APIClient(app_key=app_key, app_secret=app_secret, redirect_uri=callback_url)
# 获取授权页面网址
auth_url = client.get_authorize_url()
print auth_url

# 在浏览器中访问这个URL,会跳转到回调地址,回调地址后面跟着code,输入code
code = raw_input("Input code:")
r = client.request_access_token(code)
access_token = r.access_token
# token过期的UNIX时间
expires_in = r.expires_in
print 'access_token:',access_token
print 'expires_in:', expires_in

return access_token, expires_in

if __name__ == '__main__':
app_key = 'xxxxxxx'
app_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
callback_url = 'https://api.weibo.com/oauth2/default.html'

access_token, expires_in = get_access_token(app_key, app_secret, callback_url)
# 上面的语句运行一次后,可保存得到的access token,不必每次都申请
# access_token = 'xxxxx'
# expires_in = 'xxxxx'

client = APIClient(app_key=app_key, app_secret=app_secret, redirect_uri=callback_url)
client.set_access_token(access_token, expires_in)

idx = 1
default_msg_part_1 = 'This is no.'
default_msg_part_2 = ' msg sent automatically from benny"s robot HAHAHA'

# send a weibo with img
f = open('test.jpg', 'rb')
r = client.statuses.upload.post(status=u'test: weibo with an img. -benny', pic=f)
f.close() # APIClient不会自动关闭文件,需要手动关闭

# send text weibo every 200sec
while True:
line = default_msg_part_1 + str(idx) + default_msg_part_2
utext = unicode(line,"UTF-8")
client.post.statuses__update(status=utext)
idx = idx + 1
time.sleep(200)


效果~~~~~~~~~~~~



=====================

参考:
http://blog.sina.com.cn/s/blog_786555f6010180ji.html http://www.guokr.com/post/475564/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python weibo api