def callback(): '''用户成功登录授权后,会回调此方法,获取access_token,完成授权''' verifier = request.args.get('oauth_verifier', None) # 设置之前保存在session的request_token if 'oauth_request_token' in session: request_token = session['oauth_request_token'] del session['oauth_request_token'] else: return render_template('index.html') auth_client.set_request_token(request_token.key, request_token.secret) access_token = auth_client.get_access_token(verifier) at_key = access_token.key at_secret = access_token.secret #设定用户令牌密钥 auth_client.setToken(at_key, at_secret) #绑定用户验证信息. api = API(auth_client) #获取微博信息 weibo = api.verify_credentials() if weibo is False or weibo is None: flash(u'杯具啊,你木有开通微博吧(⊙﹏⊙)a', 'error') return render_template('index.html') #记录用户登录信息,更新用户微博资料 User.login(weibo=weibo) Weibo.set(weibo=weibo, at_key=at_key, at_secret=at_secret) #设置session session['id'] = weibo.id session.permanent = True # 跳转回最初登录前的页面 back_to_url = session.get('login_back_to_url', '/') return redirect(back_to_url)
def addFavorite(status_id): auth = OAuthHandler(APP_KEY, APP_SECRET) # Get currrent user access token from session access_token = session['oauth_access_token'] auth.setToken(access_token.key, access_token.secret) api = API(auth) api.create_favorite(status_id)
def get(self): verifier = str(self.get_argument('oauth_verifier', None)) auth_client = _oauth() # 设置之前保存在session的request_token request_token = self.session['oauth_request_token'] del self.session['oauth_request_token'] self.session.save() auth_client.set_request_token(request_token.key, request_token.secret) access_token = auth_client.get_access_token(verifier) current_user = auth_client.get_username() api = API(auth_client) # save the user info to database info = api.me() user, created = User.objects.get_or_create(weibo_id=str(info.id)) if created: user.avatar = info.profile_image_url user.name = info.screen_name user.save() self.session['me'] = info self.session['username'] = current_user # 保存access_token,以后访问只需使用access_token即可 self.session['oauth_access_token'] = access_token self.session.save() # 跳转回最初登录前的页面 back_to_url = self.session.get('login_back_to_url', '/') return self.redirect(back_to_url)
def get(self): from weibopy.auth import OAuthHandler from weibopy.api import API APP_KEY = "2567661656" APP_SECRET = "ed0a7bd30de2cc4fbffbba61dc09e60b" auth = OAuthHandler(APP_KEY, APP_SECRET, callback = 'http://localhost:8423/weibo') auth_url = auth.get_authorization_url() verifier = self.get_argument('oauth_verifier', None) if verifier: oauth_token = self.get_argument('oauth_token') REQUEST_SECRET = self.get_secure_cookie('rs') auth.set_request_token(oauth_token, REQUEST_SECRET) auth.get_access_token(verifier) api = API(auth) res = [] for msg in api.user_timeline(count=10, user_id=1231453741): txt = msg.__getattribute__('text') res.append(txt) self.write(json.dumps(res)) else: self.set_secure_cookie('rs', auth.request_token.secret) self.set_secure_cookie('ot', auth.request_token.key) self.redirect(auth_url, permanent=True) ''' Access token key: 6c21ec2ce87bf7b6c2955feee8663bc1 Access token secret: 900473fd7334c64fb7ee18f2ae6b9cf0 oauth_token_secret=900473fd7334c64fb7ee18f2ae6b9cf0&oauth_token=6c21ec2ce87bf7b6c2955feee8663bc1 api = API(auth) status = api.update_status(status="Hello Fouland") ''' pass
def get(self): verifier = str(self.get_argument('oauth_verifier', None)) auth_client = _oauth() # 设置之前保存在session的request_token request_token = self.session['oauth_request_token'] del self.session['oauth_request_token'] self.session.save() auth_client.set_request_token(request_token.key, request_token.secret) access_token = auth_client.get_access_token(verifier) current_user = auth_client.get_username() api = API(auth_client) self.session['me'] = api.me() self.session['username'] = current_user session_mc_client.set(str(api.me().id), self.session.session_id) self.set_cookie('sid', self.session.session_id) self.set_cookie('uid', str(api.me().id)) # 保存access_token,以后访问只需使用access_token即可 self.session['oauth_access_token'] = access_token self.session['platform'] = 'weibo' self.session.save() # 跳转回最初登录前的页面 back_to_url = self.session.get('login_back_to_url', '/') return self.redirect(back_to_url)
def callback(): '''用户成功登录授权后,会回调此方法,获取access_token,完成授权''' verifier = request.args.get('oauth_verifier', None) # 设置之前保存在session的request_token if 'oauth_request_token' in session: request_token = session['oauth_request_token'] del session['oauth_request_token'] else: return render_template('index.html') auth_client.set_request_token(request_token.key, request_token.secret) access_token = auth_client.get_access_token(verifier) at_key = access_token.key at_secret = access_token.secret #设定用户令牌密钥 auth_client.setToken( at_key, at_secret ) #绑定用户验证信息. api = API(auth_client) #获取微博信息 weibo = api.verify_credentials() if weibo is False or weibo is None: flash(u'杯具啊,你木有开通微博吧(⊙﹏⊙)a', 'error') return render_template('index.html') #记录用户登录信息,更新用户微博资料 User.login(weibo=weibo) Weibo.set(weibo=weibo, at_key=at_key, at_secret=at_secret) #设置session session['id'] = weibo.id session.permanent = True # 跳转回最初登录前的页面 back_to_url = session.get('login_back_to_url', '/') return redirect(back_to_url)
def press_sina_weibo(): ''''' 调用新浪微博Open Api实现通过命令行写博文,功能有待完善 author: socrates date:2012-02-06 新浪微博:@偶是正太 ''' sina_weibo_config = configparser.ConfigParser() #读取appkey相关配置文件 try: sina_weibo_config.readfp(open('sina_weibo_config.ini')) except configparser.Error: print ('read sina_weibo_config.ini failed.') #获取需要的信息 consumer_key = sina_weibo_config.get("userinfo","CONSUMER_KEY") consumer_secret =sina_weibo_config.get("userinfo","CONSUMER_SECRET") token = sina_weibo_config.get("userinfo","TOKEN") token_sercet = sina_weibo_config.get("userinfo","TOKEN_SECRET") #调用新浪微博OpenApi(python版) auth = OAuthHandler(consumer_key, consumer_secret) auth.setAccessToken(token, token_sercet) api = API(auth) #通过命令行输入要发布的内容 weibo_content = input('Please input content:') status = api.update_status(status=weibo_content) print ("Press sina weibo successful, content is: %s" % status.text)
def get(self): status_id = LastID.get_by_key_name(s_name) if not status_id: return tl_file = urllib.urlopen(t_timeline_url % t_name) timeline = json.load(tl_file) if isinstance(timeline,list): last_id = int(status_id.twitter_last_id) tweets_to_be_post = [] for tl in reversed(timeline): if int(tl['id_str']) > last_id: tweets_to_be_post.append({'id_str':tl['id_str'],'text':tl['text']}) if len(tweets_to_be_post) > 0: auth = BasicAuthHandler(s_name,s_pass) api = API(auth,source=s_app) for tweet_obj in tweets_to_be_post: cur_id = tweet_obj['id_str'] cur_tweet = tweet_obj['text'] if cur_tweet.find('#nosina') != -1 or cur_tweet.startswith('@'): continue tweet = replace_tweet(cur_tweet) try: api.update_status(tweet) status_id.twitter_last_id = cur_id status_id.put() except WeibopError,e: self.response.out.write(e) self.response.out.write('<br>')
def getFollows(self,name): self.auth.setToken(self.key,self.secret) api = API(self.auth) try: follows = api.followers_ids(screen_name=name) except Exception ,e: print e
def getFriends(self,name): self.auth.setToken(self.key,self.secret) api = API(self.auth) try: friends = api.friends_ids(screen_name=name) except Exception ,e: print e
def getWeibo(self,name): self.auth.setToken(self.key,self.secret) api = API(self.auth) start = time.time() if self.weiboflag == False: try: timeline = api.user_timeline(screen_name=name,count=50) except Exception ,e: print e for node in timeline: lst = [] lst.append(node.text.encode('utf-8')) tmp = self.getStatus(api,node.id) if tmp == []: lst.extend([0,0]) else: lst.extend(tmp) refer = getattr(node,'retweeted_status',None) if refer: lst.append(refer.text.encode('utf-8')) #print refer.mid #print refer.id tmp = self.getStatus(api,refer.mid) #print tmp if tmp == []: lst.extend[0,0] else: lst.extend(tmp) else: lst.extend(['None',0,0]) #print (len(lst)) self.updateWeibo(lst)
def GET(self): access_token=session.get('access_token',None) if not access_token: auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET,web.ctx.get('homedomain')+'/callback') auth_url = auth.get_authorization_url() session.request_token=auth.request_token web.seeother(auth_url) else: auth =OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.access_token=access_token api=API(auth) user=api.verify_credentials() user_timeline=user.timeline(count=10) print "current user is ",user.screen_name hot_list=get_hot_list() for user_tweet in user_timeline: try: hot_list.append(tuple([user_tweet.user.screen_name, user_tweet.mid, user_tweet.text, user_tweet.source, user_tweet.created_at, None, None])) except AttributeError: #no retweet_statues continue return render.index(user.screen_name,user.id,hot_list)
class Test(unittest.TestCase): consumer_key='' consumer_secret='' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth, source=self.consumer_key) def basicAuth(self, source, username, password): self.authType = 'basicauth' self.auth = BasicAuthHandler(username, password) self.api = API(self.auth,source=source) def get_privacy(self): privacy = self.api.get_privacy() self.obj = privacy ct = self.getAtt("comment") dm = self.getAtt("dm") real_name = self.getAtt("real_name") geo = self.getAtt("geo") badge = self.getAtt("badge") print ("privacy---"+ str(ct) + str(dm) + str(real_name) + str(geo) + str(badge)) def update_privacy(self): update_privacy = self.api.update_privacy(comment=0)
def mainPage(request): session = get_current_session() access_token_key = session['access_token_key'] access_token_secret = session['access_token_secret'] oauth_verifier = request.GET.get('oauth_verifier', '') get_absolute_path(request) if not access_token_key: #params['test'] = reverse('sinaweibo.views.login', args=[], kwargs={})#, current_app=context.current_app) login_url = reverse('sinaweibo.views.login', args=[], kwargs={}) #return shortcuts.render_to_response('test.html', params) return http.HttpResponseRedirect(login_url) else: auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.setToken(access_token_key, access_token_secret) api = API(auth) #myself = api.get_user(id=1894001933) #screen_name = myself. __getattribute__('screen_name') myweibo = [] myweibo_obj = api.user_timeline(count=20, page=1) for weibo in myweibo_obj: myweibo.append({'text': weibo.text, 'created_at': weibo.created_at, 'retweeted_status': hasattr(weibo, 'retweeted_status') and weibo.retweeted_status or None, 'source': weibo.source}) wrapper__at(myweibo) params = {} params['user'] = api.verify_credentials() params['result'] = myweibo template = get_template_uri(appContext, 'weibo.html') return shortcuts.render_to_response(template, params)
def get(self): status_id = LastID.get_by_key_name(s_name) if not status_id: return tl_file = urllib.urlopen(t_timeline_url % t_name) timeline = json.load(tl_file) if isinstance(timeline, list): last_id = int(status_id.twitter_last_id) tweets_to_be_post = [] for tl in reversed(timeline): if int(tl['id_str']) > last_id: tweets_to_be_post.append({ 'id_str': tl['id_str'], 'text': tl['text'] }) if len(tweets_to_be_post) > 0: auth = BasicAuthHandler(s_name, s_pass) api = API(auth, source=s_app) for tweet_obj in tweets_to_be_post: cur_id = tweet_obj['id_str'] cur_tweet = tweet_obj['text'] if cur_tweet.find('#nosina') != -1 or cur_tweet.startswith( '@'): continue tweet = replace_tweet(cur_tweet) try: api.update_status(tweet) status_id.twitter_last_id = cur_id status_id.put() except WeibopError, e: self.response.out.write(e) self.response.out.write('<br>')
def get(self): self.response.out.write('TwiNa service is running now!<br>') last_id = LastID.get_by_key_name(s_name) if not last_id: self.response.out.write( """This is your first time to this page!<br>""") self.response.out.write( """TwiNa will now synchronize your last tweet!<br>""") auth = BasicAuthHandler(s_name, s_pass) api = API(auth, source=s_app) tl_file = urllib.urlopen(t_timeline_url % t_name) timeline = json.load(tl_file) tweet = replace_tweet(timeline[0]['text']) status_id = LastID(key_name=s_name) status_id.twitter_last_id = timeline[0]['id_str'] status_id.put() try: api.update_status(tweet) except WeibopError, e: self.response.out.write(e) else: self.response.out.write( 'Your Last Tweet has already been synchronize:<br>') self.response.out.write("<b>%s</b>" % timeline[0]['text'])
def authorization(self): """ 开发者认证 """ auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET) auth.setToken(key.TOKEN, key.TOKEN_SECRET) self.api = API(auth) self.cursor = cursor
class Test(unittest.TestCase): consumer_key = '' consumer_secret = '' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth) def basicAuth(self, source, username, password): self.auth = BasicAuthHandler(username, password) self.api = API(self.auth, source=source) def friends_timeline(self): timeline = self.api.friends_timeline(count=2, page=1) for line in timeline: self.obj = line mid = self.getAtt("id") text = self.getAtt("text") print("friends_timeline---" + str(mid) + ":" + text) def comments_timeline(self): timeline = self.api.comments_timeline(count=2, page=1) for line in timeline: self.obj = line mid = self.getAtt("id") text = self.getAtt("text") print("comments_timeline---" + str(mid) + ":" + text) def user_timeline(self): timeline = self.api.user_timeline(count=5, page=1) for line in timeline: self.obj = line mid = self.getAtt("id") text = self.getAtt("text") created_at = self.getAtt("created_at") print("user_timeline---" + str(mid) + ":" + str(created_at) + ":" + text) timeline = self.api.user_timeline(count=20, page=2) def public_timeline(self): timeline = self.api.public_timeline(count=2, page=1) for line in timeline: self.obj = line mid = self.getAtt("id") text = self.getAtt("text") print("public_timeline---" + str(mid) + ":" + text)
def post(self, site): if site == "wb": content = self.get_argument("content") access_token = self.session.get("oauth_access_token") auth = OAuthHandler(options.SINA_APP_KEY, options.SINA_APP_SECRET) auth.set_access_token(access_token.key, access_token.secret) api = API(auth) api.update_status(content) self.finish(json.dumps("success"))
def newmessage(self, message, lat=None, long=None): log.debug('new message: %s' % message) auth = OAuthHandler(APP_KEY, APP_SECRET) info = user.get_app('sina', self.email) auth.setToken(info['access_token'], info['access_secret']) api = API(auth) api.update_status(message) log.debug('new message done.') return True
def get_username(self): if self.username is None: api = API(self) user = api.verify_credentials() if user: self.username = user.screen_name else: raise WeibopError("Unable to get username, invalid oauth token!") return self.username
class Test(unittest.TestCase): consumer_key = '' consumer_secret = '' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth) def basicAuth(self, source, username, password): self.auth = BasicAuthHandler(username, password) self.api = API(self.auth, source=source) def direct_message(self): messages = self.api.direct_messages() mid = '' for msg in messages: self.obj = msg mid = self.getAtt("id") text = self.getAtt("text") print("direct_message---" + str(mid) + ":" + text) return mid def sent_direct_messages(self): messages = self.api.sent_direct_messages() for msg in messages: self.obj = msg mid = self.getAtt("id") text = self.getAtt("text") print("sent_direct_messages---" + str(mid) + ":" + text) def new_direct_message(self): msg = self.api.new_direct_message(id=1114365581, text='directMessages--test-²âÊÔ-' + str(time.time())) self.obj = msg mid = self.getAtt("id") text = self.getAtt("text") print("new_direct_message---" + str(mid) + ":" + text) def destroy_direct_message(self, id): msg = self.api.destroy_direct_message(id) self.obj = msg mid = self.getAtt("id") text = self.getAtt("text") print("destroy_direct_message---" + str(mid) + ":" + text)
class Test(unittest.TestCase): consumer_key='' consumer_secret='' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth) def basicAuth(self, source, username, password): self.auth = BasicAuthHandler(username, password) self.api = API(self.auth,source=source) def friends_timeline(self): timeline = self.api.friends_timeline(count=2, page=1) for line in timeline: self.obj = line mid = self.getAtt("id") text = self.getAtt("text") print("friends_timeline---"+ str(mid) +":"+ text) def comments_timeline(self): timeline = self.api.comments_timeline(count=2, page=1) for line in timeline: self.obj = line mid = self.getAtt("id") text = self.getAtt("text") print("comments_timeline---"+ str(mid) +":"+ text) def user_timeline(self): timeline = self.api.user_timeline(count=5, page=1) for line in timeline: self.obj = line mid = self.getAtt("id") text = self.getAtt("text") created_at = self.getAtt("created_at") print("user_timeline---"+ str(mid) +":"+ str(created_at)+":"+ text) timeline = self.api.user_timeline(count=20, page=2) def public_timeline(self): timeline = self.api.public_timeline(count=2, page=1) for line in timeline: self.obj = line mid = self.getAtt("id") text = self.getAtt("text") print("public_timeline---"+ str(mid) +":"+ text)
def __init__(self): #设定网页应用回调页面(桌面应用设定此变量为空) BACK_URL = "" #验证开发者密钥. auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL) #设定用户令牌密钥. auth.setToken(TOKEN_KEY, TOKEN_SECRET) #绑定用户验证信息. self.api = API(auth)
class Test(unittest.TestCase): consumer_key='' consumer_secret='' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth, source=self.consumer_key) def basicAuth(self, source, username, password): self.authType = 'basicauth' self.auth = BasicAuthHandler(username, password) self.api = API(self.auth,source=source) def tags(self): tags = self.api.tags(user_id=1377583044) for line in tags: self.obj = line tagid=self.getAtt("id") value = self.getAtt(tagid) print (tagid,value) def tag_create(self ,message): # message = message.encode("utf-8") tag_create = self.api.tag_create(tags=message) for line in tag_create: self.obj = line tagid = self.getAtt("tagid") print ("tag_create---"+tagid) def tag_suggestions(self): tag_suggestions=self.api.tag_suggestions() for line in tag_suggestions: self.obj = line id = self.getAtt("id") value = self.getAtt("value") print ("tag_suggestions---"+ id +":"+ value) def tag_destroy(self,tag_id): tag_destroy=self.api.tag_destroy(tag_id) self.obj=tag_destroy result=self.getAtt("result") print ("tag_destroy---"+ result) def tag_destroy_batch(self,tag_ids): tag_destroy_batch=self.api.tag_destroy_batch(tag_ids) for line in tag_destroy_batch: self.obj = line tagid=self.getAtt("tagid") print ("tag_destroy_batch---"+ tagid)
def analyze(self,query): if query=="" or query is None: web.seeother("/") access_token=session.get('access_token',None) auth =OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.access_token=access_token api=API(auth) repost_timeline=api.repost_timeline(count=10) print repost_timeline logging.info("analyzing query %s " % (query))
def get(self): auth = BasicAuthHandler("user", "password") api = API(auth, source="3990552168") timeline = api.user_timeline(count=1, page=1)[0] tweet = Tweet.all().get() if not tweet: tweet = Tweet(text=timeline.text, date=timeline.created_at) tweet.text = timeline.text tweet.date = timeline.created_at tweet.put()
def searchUser(self,name): self.auth.setToken(self.key,self.secret) api = API(self.auth) try : user = api.get_user(screen_name=name) #print user.id data = (user.screen_name.encode('utf-8'),user.location.encode('utf-8'),user.followers_count,user.friends_count,user.statuses_count,user.profile_image_url) return data except Exception ,e: pass
def updateWeiboStatus(message): auth = OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET) auth.setToken(ACCESS_TOKEN_KEY,ACCESS_TOKEN_SECRET) api=API(auth) message = message.encode("utf-8") status = api.update_status(status=message) from time import sleep sleep(5)
def get(self): verifier = self.request.get('oauth_verifier') logging.info('verify id = %s' % verifier) signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1() # Get token - key and secret from memcache that we set on SinaOauthPhaseOne tokenstr = memcache.get("PK_"+self.request.get('id')) memcache.delete("PK_"+self.request.get('id')) token = oauth.OAuthToken.from_string(tokenstr) consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET) client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZATION_URL) oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, token=token, verifier=verifier, http_url=client.access_token_url) oauth_request.sign_request(signature_method_hmac_sha1, consumer, token) # Finally get access_token after verifier is matched. access_token = client.fetch_access_token(oauth_request) logging.info('Sina Authorized access_token = %s' % access_token) # Set cookie into browser in case for further use. self.response.headers.add_header('Set-Cookie', 'oauth_key=' + access_token.key + cookie) self.response.headers.add_header('Set-Cookie', 'oauth_secret=' + access_token.secret + cookie) # Call Sina weibopy API auth.OAuthHandler() and set access_token to # fetch access_resource aka:user resource. auth_access_resource = OAuthHandler( consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET) auth_access_resource.set_access_token(access_token.key, access_token.secret) # API() inherits auth_access_resource return. api = API(auth_access_resource) # I call api.verify_credentials instead of use auth.OAuthHandler.get_username username = api.verify_credentials() if username: self.username = username.screen_name self.response.headers.add_header('Set-Cookie', 'sina_username='******'Sina username: %s' % self.username) else: logging.info('NO SINA USER') self.redirect('/')
class Test(unittest.TestCase): consumer_key='' consumer_secret='' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth) def basicAuth(self, source, username, password): self.auth = BasicAuthHandler(username, password) self.api = API(self.auth,source=source) def direct_message(self): messages = self.api.direct_messages() mid = '' for msg in messages: self.obj = msg mid = self.getAtt("id") text = self.getAtt("text") print("direct_message---"+ str(mid) +":"+ text) return mid def sent_direct_messages(self): messages = self.api.sent_direct_messages() for msg in messages: self.obj = msg mid = self.getAtt("id") text = self.getAtt("text") print("sent_direct_messages---"+ str(mid) +":"+ text) def new_direct_message(self): msg = self.api.new_direct_message(id=1114365581,text='directMessages--test-²âÊÔ-'+ str(time.time())) self.obj = msg mid = self.getAtt("id") text = self.getAtt("text") print("new_direct_message---"+ str(mid) +":"+ text) def destroy_direct_message(self, id): msg = self.api.destroy_direct_message(id) self.obj = msg mid = self.getAtt("id") text = self.getAtt("text") print("destroy_direct_message---"+ str(mid) +":"+ text)
def get(self): verifier = self.request.get('oauth_verifier') logging.info('verify id = %s' % verifier) signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1() # Get token - key and secret from memcache that we set on SinaOauthPhaseOne tokenstr = memcache.get("PK_" + self.request.get('id')) memcache.delete("PK_" + self.request.get('id')) token = oauth.OAuthToken.from_string(tokenstr) consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET) client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZATION_URL) oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, token=token, verifier=verifier, http_url=client.access_token_url) oauth_request.sign_request(signature_method_hmac_sha1, consumer, token) # Finally get access_token after verifier is matched. access_token = client.fetch_access_token(oauth_request) logging.info('Sina Authorized access_token = %s' % access_token) # Set cookie into browser in case for further use. self.response.headers.add_header( 'Set-Cookie', 'oauth_key=' + access_token.key + cookie) self.response.headers.add_header( 'Set-Cookie', 'oauth_secret=' + access_token.secret + cookie) # Call Sina weibopy API auth.OAuthHandler() and set access_token to # fetch access_resource aka:user resource. auth_access_resource = OAuthHandler(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET) auth_access_resource.set_access_token(access_token.key, access_token.secret) # API() inherits auth_access_resource return. api = API(auth_access_resource) # I call api.verify_credentials instead of use auth.OAuthHandler.get_username username = api.verify_credentials() if username: self.username = username.screen_name self.response.headers.add_header( 'Set-Cookie', 'sina_username='******'Sina username: %s' % self.username) else: logging.info('NO SINA USER') self.redirect('/')
def update_weibo(self,message): self.load_setting() self.auth.set_request_token(self.setting['request_token'],self.setting['request_token_secret']) self.auth.set_access_token(self.setting['access_token'],self.setting['access_token_secret']) api = API(self.auth) is_updated = api.update_status(message) if(is_updated): print '你又在微博上跟大家说了一句话~~'
def new_direct_message (self,who,message): self.load_setting() self.auth.set_request_token(self.setting['request_token'],self.setting['request_token_secret']) self.auth.set_access_token(self.setting['access_token'],self.setting['access_token_secret']) api = API(self.auth) is_updated = api.new_direct_message(who,message) if(is_updated): print '成功!~~~'
def GET(self): try: auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET) auth.access_token = session['access_token'] api = API(auth) user = api.verify_credentials() fan = [] next_cursor = -1 while next_cursor != 0: timeline = api.followers(user.id, '', '', '', next_cursor) if isinstance(timeline, tuple): next_cursor = timeline[1] for line in timeline[0]: fid = line.__getattribute__("id") fname = line.__getattribute__("screen_name") fan.append((fid, fname)) else: next_cursor = 0 for line in timeline: fid = line.__getattribute__("id") fname = line.__getattribute__("screen_name") fan.append((fid, fname)) friend = [] next_cursor = -1 while next_cursor != 0: timeline = api.friends(user.id, '', '', '', next_cursor) if isinstance(timeline, tuple): next_cursor = timeline[1] for line in timeline[0]: frid = line.__getattribute__("id") frname = line.__getattribute__("screen_name") friend.append((frid, frname)) else: next_cursor = 0 for line in timeline: frid = line.__getattribute__("id") frname = line.__getattribute__("screen_name") friend.append((frid, frname)) #获取我的粉丝中还不是我的关注对象 fanNotAttention = list(set(fan).difference(set(friend))) nu = len(fanNotAttention) if nu == 0: return render_template('noattentionok.html', nu=nu) else: return render_template('noattention.html', nu=nu, fanNotAttention=fanNotAttention) except: info = "亲,系统繁忙,请稍后再试......,系统在3秒后自动返回..." return render_template('error.html', info=info.decode('utf-8'))
def follow_all(user, auth): api = API(auth) candidates = Candidate.get_by_user(user).filter(follow_date=None) for c in candidates: try: d = api.create_friendship(user_id=c.weiboid) c.follow_date = datetime.datetime.now() c.save() except WeibopError, e: #没有接口能够轻易的判断出错误原因。 #很可能是已经关注了 c.delete()
def follow_all(user, auth): api = API(auth) candidates = Candidate.get_by_user(user).filter(follow_date = None) for c in candidates: try: d = api.create_friendship(user_id = c.weiboid) c.follow_date = datetime.datetime.now() c.save() except WeibopError,e: #没有接口能够轻易的判断出错误原因。 #很可能是已经关注了 c.delete()
class SinaClient: def __init__(self, key, secret): self.auth=OAuthHandler(key,secret) def get_auth_url(self): return self.auth.get_authorization_url() def set_access_token(self,token): key,secret=token.split('|') self.auth.setToken(key,secret) self.api=API(self.auth) def get_access_token(self): token=self.auth.access_token return token.key+'|'+token.secret def set_request_token(self,token): key,secret=token.split('|') self.auth.request_token=oauth.OAuthToken(key,secret) def get_request_token(self): token=self.auth.request_token return token.key+'|'+token.secret def set_verifier(self,verifier): self.auth.get_access_token(verifier) self.api=API(self.auth) def send_msg(self,msg,coord=None): lat,long=self.get_lat_long(coord) msg=msg.encode('utf-8') status=self.api.update_status(status=msg,lat=lat,long=long) return status def send_pic(self,msg,pic,coord=None): lat,long=self.get_lat_long(coord) msg=msg.encode('utf-8') status=self.api.upload(pic,status=msg,lat=lat,long=long) return status def get_timeline(self): return self.request(SINA_USER_TIMELINE_URL) def get_lat_long(self,coord): if not coord: return (None,None) return map(lambda x:str(x),coord) def get_user(self): return self.api.verify_credentials()
class Bot: def __init__(self): BACK_URL = "" #验证开发者密钥. auth = OAuthHandler( APP_KEY, APP_SECRET, BACK_URL ) auth.setToken( BOT_TOKEN_KEY, BOT_TOKEN_SECRET ) self.api = API(auth) def send(self, message): try: return self.api.update_status(message) except WeibopError, e: return self.api.user_timeline(count=1)[0]
class Bot: def __init__(self): BACK_URL = "" #验证开发者密钥. auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL) auth.setToken(BOT_TOKEN_KEY, BOT_TOKEN_SECRET) self.api = API(auth) def send(self, message): try: return self.api.update_status(message) except WeibopError, e: return self.api.user_timeline(count=1)[0]
def update_weibo(self,message): self.load_setting() self.auth.set_request_token(self.setting['request_token'], self.setting['request_token_secret']) self.auth.set_access_token(self.setting['access_token'], self.setting['access_token_secret']) api = API(self.auth) is_updated = api.update_status(message) if(is_updated): print '你又在微博上跟大家说了一句话~~'
class Test(unittest.TestCase): consumer_key = '' consumer_secret = '' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth) def basicAuth(self, source, username, password): self.auth = BasicAuthHandler(username, password) self.api = API(self.auth, source=source) def create_friendship(self): user = self.api.create_friendship(id=1114365581) self.obj = user uid = self.getAtt("id") screen_name = self.getAtt("screen_name") print("create_friendship---" + str(uid) + ":" + screen_name) def destroy_friendship(self): user = self.api.destroy_friendship(id=1114365581) self.obj = user uid = self.getAtt("id") screen_name = self.getAtt("screen_name") print("destroy_friendship---" + str(uid) + ":" + screen_name) def exists_friendship(self): self.obj = self.api.exists_friendship(user_a=1772333754, user_b=1773365880) friends = self.getAtt("friends") print("exists_friendship--- " + str(friends)) def show_friendship(self, uid): showList = self.api.show_friendship(target_id=uid) for obj in showList: self.obj = obj uid = self.getAtt("id") screen_name = self.getAtt("screen_name") print("show_friendship---" + str(uid) + ":" + screen_name)
class Test(unittest.TestCase): consumer_key = '' consumer_secret = '' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def auth(self): if len(self.consumer_key) == 0: print("Please set consumer_key£¡£¡£¡") return if len(self.consumer_key) == 0: print("Please set consumer_secret£¡£¡£¡") return self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) auth_url = self.auth.get_authorization_url() print('Please authorize: ' + auth_url) verifier = input('PIN: ').strip() self.auth.get_access_token(verifier) self.api = API(self.auth) def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth) def update(self, message): status = self.api.update_status(message) self.obj = status id = self.getAtt("id") text = self.getAtt("text") print("update,id=" + str(id) + ",text=" + text) def destroy_status(self, id): status = self.api.destroy_status(id) self.obj = status id = self.getAtt("id") text = self.getAtt("text") print("update---" + str(id) + ":" + text)
class Test(unittest.TestCase): consumer_key='' consumer_secret='' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def auth(self): if len(self.consumer_key) == 0: print("Please set consumer_key£¡£¡£¡") return if len(self.consumer_key) == 0: print("Please set consumer_secret£¡£¡£¡") return self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) auth_url = self.auth.get_authorization_url() print('Please authorize: ' + auth_url) verifier = input('PIN: ').strip() self.auth.get_access_token(verifier) self.api = API(self.auth) def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth) def update(self, message): status = self.api.update_status(message) self.obj = status id = self.getAtt("id") text = self.getAtt("text") print("update,id="+ str(id) +",text="+ text) def destroy_status(self, id): status = self.api.destroy_status(id) self.obj = status id = self.getAtt("id") text = self.getAtt("text") print("update---"+ str(id) +":"+ text)
def collect_candidate(user, auth, keyword): api = API(auth) weibo_list = api.search(q=keyword) for weibo in weibo_list: o = Candidate.get_by_id(user, weibo.from_user_id) if o is not None: o.priority += 1 o.save() else: o = Candidate() o.name = weibo.from_user o.weiboid = weibo.from_user_id o.user = user o.priority = 1 o.save()
class Test(unittest.TestCase): consumer_key = '' consumer_secret = '' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth, source=self.consumer_key) def basicAuth(self, source, username, password): self.authType = 'basicauth' self.auth = BasicAuthHandler(username, password) self.api = API(self.auth, source=source) def counts(self): counts = self.api.counts(ids='1864372538,1484854960,1877120192') for count in counts: self.obj = count mid = self.getAtt("id") comments = self.getAtt("comments") rt = self.getAtt("rt") print("mentions---" + str(mid) + ":" + str(comments) + ":" + str(rt))
def post_to_wb(request): if request.method == 'POST': success = "" access_token = request.session['oauth_access_token'] auth = OAuthHandler(SINA_APP_KEY, SINA_APP_SECRET) auth.set_access_token(access_token.key, access_token.secret) api = API(auth) try: content = request.POST.get("content") api.update_status(content) success = "成功发布" except: raise success = "失败" return HttpResponseRedirect('/status') return HttpResponseRedirect('/status')
class test(unittest.TestCase): consumer_key = '' consumer_secret = '' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth) def basicAuth(self, source, username, password): self.auth = BasicAuthHandler(username, password) self.api = API(self.auth, source=source) def friends(self): timeline = self.api.friends() for line in timeline: self.obj = line fid = self.getAtt("id") name = self.getAtt("screen_name") print("friends---" + str(fid) + ":" + name)
def auth(self): if len(self.consumer_key) == 0: print("Please set consumer_key£¡£¡£¡") return if len(self.consumer_key) == 0: print("Please set consumer_secret£¡£¡£¡") return self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) auth_url = self.auth.get_authorization_url() print('Please authorize: ' + auth_url) verifier = input('PIN: ').strip() self.auth.get_access_token(verifier) self.api = API(self.auth)
class Test(unittest.TestCase): consumer_key = '' consumer_secret = '' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth) def basicAuth(self, source, username, password): self.auth = BasicAuthHandler(username, password) self.api = API(self.auth, source=source) def unread(self): count = self.api.unread() self.obj = count mentions = self.getAtt("mentions") comments = self.getAtt("comments") followers = self.getAtt("followers") dm = self.getAtt("dm") print("mentions---" + str(mentions) + ":" + str(comments) + ":" + str(followers) + ":" + str(dm))
class Test(unittest.TestCase): consumer_key = '' consumer_secret = '' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth, source=self.consumer_key) def basicAuth(self, source, username, password): self.auth = BasicAuthHandler(username, password) self.api = API(self.auth, source=source) def update_profile_image(self, filename): user = self.api.update_profile_image(filename) self.obj = user id = self.getAtt("id") profile_image_url = self.getAtt("profile_image_url") print("update,uid=" + str(id) + ",profile_image_url=" + profile_image_url)
def press_sina_weibo(): ''''' 调用新浪微博Open Api实现通过命令行写博文,功能有待完善 author: socrates date:2012-02-06 新浪微博:@没耳朵的羊 ''' sina_weibo_config = configparser.ConfigParser() #读取appkey相关配置文件 try: sina_weibo_config.readfp(open('sina_weibo_config.ini')) except configparser.Error: print('read sina_weibo_config.ini failed.') #获取需要的信息 consumer_key = sina_weibo_config.get("userinfo", "CONSUMER_KEY") consumer_secret = sina_weibo_config.get("userinfo", "CONSUMER_SECRET") token = sina_weibo_config.get("userinfo", "TOKEN") token_sercet = sina_weibo_config.get("userinfo", "TOKEN_SECRET") #调用新浪微博OpenApi(python版) auth = OAuthHandler(consumer_key, consumer_secret) auth.setAccessToken(token, token_sercet) api = API(auth) return api
def GET(self): #获取noattentionok.html传过来的数据 data = web.input() on = [] try: auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET) auth.access_token = session['access_token'] api = API(auth) """ 获取noattention.html页面传过来的uid,通过checkbox,由于有一个全选按钮,如果点击,则去掉 """ for x in data: on.append(x) try: on.remove('checkbox2') except: pass nu = len(on) if nu == 0: pass if nu > 60: on = on[:60] nu = 60 """ 一次最多加60次关注 """ map(api.create_friendship, on) info = "恭喜您已成功关注%d位用户....." % nu return render_template('success.html', info=info.decode('utf-8')) except: info = "亲,系统繁忙,请稍后再试......,系统在3秒后自动返回..." return render_template('error.html', info=info.decode('utf-8'))
class Test(unittest.TestCase): consumer_key = '' consumer_secret = '' def __init__(self): """ constructor """ def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception as e: print(e) return '' def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth) def basicAuth(self, source, username, password): self.auth = BasicAuthHandler(username, password) self.api = API(self.auth, source=source) def repost(self, id, message): status = self.api.repost(id, message) self.obj = status id = self.getAtt("id") text = self.getAtt("text") print("repost---" + str(id) + ":" + text)
def GET(self): #获取attentionnotfan.html传过来的数据 data = web.input() on = [] try: auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET) auth.access_token = session['access_token'] api = API(auth) for x in data: on.append(x) try: #同理,由于有全选按钮..... on.remove('checkbox2') except: pass nu = len(on) if nu == 0: pass #取消关注 map(api.destroy_friendship, on) info = "恭喜您已成功取消关注%d位用户....." % nu return render_template('success.html', info=info.decode('utf-8')) except: info = "亲,系统繁忙,请稍后再试......,系统在3秒后自动返回..." return render_template('error.html', info=info.decode('utf-8'))