Skip to content

Instantly share code, notes, and snippets.

@ahxxm
Created October 7, 2015 10:11
Show Gist options
  • Save ahxxm/98bc66cedb5c95f91576 to your computer and use it in GitHub Desktop.
Save ahxxm/98bc66cedb5c95f91576 to your computer and use it in GitHub Desktop.
weibo同步
from weibo import Client
from twitter import *
import json
import re
import requests
import Image
from StringIO import StringIO
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
# Sina
APP_KEY = '='
APP_SECRET = ''
CALLBACK_URL = ''
c = Client(APP_KEY, APP_SECRET, CALLBACK_URL, username='', password='')
# Twitter Oauth, might need oauth_dance
auth = OAuth(
consumer_key='',
consumer_secret='',
token='',
token_secret=''
)
t = Twitter(auth=auth)
# See if there is 'last.txt': last fetched weibo's id.
try:
w = open('/root/bots/sinalast.txt')
last = int(w.read())
w.close()
# Deal with them. 'since_id' means 'greater than', no equal.
x = c.get('statuses/home_timeline', count=100, since_id=last)
except IOError:
# write last and break, this part should be executed only once when started.
x = c.get('statuses/home_timeline')
# Save sync states
last = str(x['statuses'][0]['id'])
w = open('/root/bots/sinalast.txt', 'w')
w.write(last)
w.close()
# Concatinate IMAGE
# Credits: http://29a.ch/2009/5/14/concatenating-images-using-python
def image_process(imagelink):
# input list of images
# output one image object for uploading
images = []
for link in imagelink:
link = link['thumbnail_pic'].replace('thumbnail', 'large')
try:
image = Image.open(StringIO(requests.get(link, timeout=3).content))
images.append(image)
except:
pass
w = sum(i.size[0] for i in images)
mh = max(i.size[1] for i in images)
result = Image.new("RGB", (w, mh), color=(255,255,255))
x = 0
for i in images:
result.paste(i, (x, 0))
x += i.size[0]
result.save('/root/bots/sinalast.jpg')
# Sync
# Logic inside
def insert_and_post(tweet):
# Judge
username = tweet['user']['name']
content = tweet['text']
jsed = str(json.dumps(tweet, ensure_ascii=False))
# 1. if it is retweeting, if so,
# See text length: longer than 8 HanZi then post it, and post origin weibo;
# And, consider only images of retweeted_status.
if tweet.has_key('retweeted_status'):
text = re.findall('.*?(?=\/\/\@)', content) # Content till first '//@'
real_text = text[0] if len(text)>0 else content # Extreme case
if len(real_text)>8 :
contentlength = 140 - len(username) - 10
tweetcontent = str(username) + ": " + str(real_text[:contentlength])
try:
t.statuses.update(status=tweetcontent)
except:
pass
tweet = tweet['retweeted_status']
username = tweet['user']['name']
content = tweet['text']
# 2. Image or not
if tweet.has_key('original_pic'):
imagelinks = tweet['pic_urls']
image_process(imagelinks)
# now we have image 'last.jpg', which takes 23/140 of a tweet.
#imagelink = str(tweet['original_pic'])
content_available = 140 - 26 - len(username) # Because ": " takes another 2. In case twimg length ++..
w = open('/root/bots/sinalast.jpg', 'rb')
image = w.read()
tweetcontent = str(username) + ": " + str(content[:content_available])
params = {"media[]": image, "status": tweetcontent}
try:
t.statuses.update_with_media(**params)
except:
pass
w.close()
else:
# post without imagelink
content_available = 140 - len(username) - 3
tweetcontent = str(username) + ": " + str(content[:content_available])
try:
t.statuses.update(status=tweetcontent)
except:
pass
# contents we need
statuses = x['statuses'] # newest first so insert last first
statusess = reversed(statuses)
for weibo in statusess:
print weibo['id']
insert_and_post(weibo)
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36'
}
aqi = requests.get('http://aqicn.org/aqicn/json/android/Beijing/json', headers=headers).json()['aqi']
aqistatus = 'AQI is ' + str(aqi)
t.statuses.update(status=aqistatus)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment