用python自動發微博

……剛剛全部寫完了點發布……結果什麼都沒保存……內心好憂傷。

終極目標是用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/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章