Created
May 28, 2012 14:23
-
-
Save s5unty/2819432 to your computer and use it in GitHub Desktop.
同步 twitter 到 sina weibo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import httplib | |
import urllib | |
import json | |
import base64 | |
import cPickle as p | |
import sys | |
reload(sys) | |
sys.setdefaultencoding('utf8') | |
#====需要修改下面g_开头的变量为你自己的 | |
g_since_id_file = "/sun/.last_tweet_id" | |
def get_since_id(): | |
try: | |
f = file(g_since_id_file) | |
id = p.load(f) | |
f.close() | |
return id | |
except IOError: | |
return None | |
def set_since_id(id): | |
if id: | |
try: | |
f = file(g_since_id_file, 'w') | |
p.dump(id, f) | |
f.close() | |
except IOError: | |
pass | |
def sina(msg): | |
sys.path.append(".sina/") | |
from weibopy.auth import OAuthHandler | |
from weibopy.api import API | |
consumer_key = '#自己申请的新浪API#' | |
consumer_secret = '#自己申请的新浪API#' | |
token = '#自己申请的新浪API#' | |
tokenSecret = '#自己申请的新浪API#' | |
auth = OAuthHandler(consumer_key, consumer_secret) | |
auth.setToken(token, tokenSecret) | |
api = API(auth) | |
status = api.update_status(status=msg) | |
def twitter(username, last_id): | |
# 如果last_id为空,那么我们只是取得当前的since_id而不进行同步 | |
if last_id: | |
uri="/1/statuses/user_timeline.json?screen_name=%s&trim_user=true&count=1&since_id=%s"%(username, last_id) | |
else: | |
uri="/1/statuses/user_timeline.json?screen_name=%s&trim_user=true&count=1"%(username) | |
print uri | |
conn = httplib.HTTPConnection("api.twitter.com") | |
conn.request("GET", uri) | |
ret = conn.getresponse() | |
if ret.status == 200: | |
update_id = None | |
j = json.load(ret) | |
# 使其按时间顺序排列 | |
for info in j: | |
print info['id'], info['in_reply_to_user_id'], info['text'] | |
update_id = info['id'] | |
# 过滤回复消息 | |
if info['in_reply_to_user_id'] == None: | |
text = info['text'] | |
if last_id: | |
print "parser msg: ", text | |
sina(text) | |
set_since_id(update_id) | |
else: | |
print "twitter error: ", ret.status, ret.reason | |
conn.close() | |
last_id = get_since_id() | |
print "last_id = ", last_id | |
twitter("#你的twitter用户名#", last_id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment