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)
class getData(): def __init__(self,flaglt): APP_KEY = '190802369' APP_SECRET = 'fb4ce1e3a4b049abb75f104d7a7439d7' BACK_URL = '' self.auth = OAuthHandler(APP_KEY,APP_SECRET,BACK_URL) with open('entry.pickle','rb') as f: entry = pickle.load(f) self.key = entry['key'] self.secret = entry['secret'] self.followflag = flaglt[0] self.friendflag = flaglt[1] self.weiboflag = flaglt[2] def getFlagStatus(self): return (self.followflag,self.friendflag,self.weiboflag) 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 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 authorization(self): """ 开发者认证 """ auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET) auth.setToken(key.TOKEN, key.TOKEN_SECRET) self.api = API(auth) self.cursor = cursor
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 __init__(self): # 设定网页应用回调页面(桌面应用设定此变量为空) BACK_URL = "" # 验证开发者密钥. auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL) # 设定用户令牌密钥. auth.setToken(TOKEN_KEY, TOKEN_SECRET) # 绑定用户验证信息. self.api = API(auth)
def WeiboAuthV1(userinfo): api = None try: auth = OAuthHandler(WEIBO_APP_KEY, WEIBO_APP_SECRET) auth.setToken(userinfo.weibo_access_token, userinfo.weibo_access_token_secret) api = API(auth) except Exception as e: logging.info("WeiboAuth error %s " % e) return api
def __init__(self): #设定网页应用回调页面(桌面应用设定此变量为空) BACK_URL = "" #验证开发者密钥. auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL) #设定用户令牌密钥. auth.setToken(TOKEN_KEY, TOKEN_SECRET) #绑定用户验证信息. self.api = API(auth)
def api(): token=get_access_token('w..','c..') #input your weibo id and password here# atKey =token['oauth_token'] atSecret = token['oauth_token_secret'] from weibopy.error import WeibopError auth = OAuthHandler(APP_KEY, APP_SECRET) auth.setToken( atKey, atSecret ) api = API(auth) # bind the authentication information to connect to API return api
def api(): token = get_access_token('w..', 'c..') #input your weibo id and password here# atKey = token['oauth_token'] atSecret = token['oauth_token_secret'] from weibopy.error import WeibopError auth = OAuthHandler(APP_KEY, APP_SECRET) auth.setToken(atKey, atSecret) api = API(auth) # bind the authentication information to connect to API return api
def __init__(self,app_key="3146673438",app_secret="f65a02335629c4ff5c4a5314fedfa97f"): app_key=app_key app_secret=app_secret file=open("token","r") token_key=file.readline() token_secret=file.readline() file.close() auth=OAuthHandler(app_key,app_secret) auth.setToken(token_key[0:-1],token_secret) self.api=API(auth)
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 auth(self): # Check Sina user logged in or not. self.sina_username = self.request.cookies.get("sina_username") if self.sina_username: oauth_key = self.request.cookies.get("oauth_key") oauth_secret = self.request.cookies.get("oauth_secret") auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.setToken(oauth_key, oauth_secret) self.api = API(auth) return True return False
def wrapper(self, *args, **kwargs): auth = OAuthHandler(SINA_CONSUME_KEY, SINA_CONSUME_SECRET) request_token = self.SESSION['oauth_access_token'] if request_token: auth.setToken(request_token.key, request_token.secret) api = API(auth) self.__setattr__('sapi', api) else: to_url = '/auth?to_url='+self.request.path self.redirect(to_url) return method(self, *args, **kwargs)
class WeiboBackup(object): """ 新浪微博自动备份. """ def __init__(self): self.hdl = OAuthHandler(config.APP_KEY, config.APP_SECRET) self.api = None self.writer = None self.token = {} self.auth() def auth(self): try: with open("../" + config.TOKEN_FILE) as f: self.token = pickle.load(f) self.hdl.setToken(self.token["key"], self.token["secret"]) self.api = API(self.hdl) except Exception as e: print e def get_auth_url(self): return self.hdl.get_authorization_url() def get_data(self, screen_name, page): count = 200 while True: try: res = self.api.user_timeline(screen_name=screen_name, count=count, page=page) if len(res) == 0: return page else: for status in res: text = status.text retweet = getattr(status, "retweeted_status", False) if retweet: text = text + "//" + retweet.text text = text.encode("utf-8") self.writer.append(text) page = page + 1 except Exception as e: print e def backup(self, screen_name, filename=""): if filename: self.writer = Writer(filename) else: self.writer = [] page, alert_num = 1, 0 while alert_num < ALERT_MAX_TIMES: page = self.get_data(screen_name, page) alert_num += 1 return self.writer
class sinaAPI(): def __init__(self, token, tokenSecret): self.auth = OAuthHandler(consumer_key, consumer_secret) self.auth.setToken(token, tokenSecret) self.api = API(self.auth) def attr(self,obj,key): try: return obj.__getattribute__(key) except Exception,e: #print e return ''
class sinaAPI(): def __init__(self, token, tokenSecret): self.auth = OAuthHandler(consumer_key, consumer_secret) self.auth.setToken(token, tokenSecret) self.api = API(self.auth) def attr(self, obj, key): try: return obj.__getattribute__(key) except Exception, e: #print e return ''
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 myapi(): def __init__(self,username="******",psw="123456789"): #self.logfile=log_stream.log_stream("sina_sdk") global gconsumer_key global gconsumer_secret global gtoken global gtokenSecret #创建一个opener self.__cJar=cookielib.CookieJar() self.__opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(self.__cJar)) self.__opener.addheaders=[('User-agent','Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)')] urllib2.install_opener(self.__opener) #创建一个auth对象 self.__auth=OAuthHandler(gconsumer_key,gconsumer_secret) self.__auth.setToken(gtoken,gtokenSecret) #创建api对象 self.__api=API(self.__auth) def __del__(self): pass def __get_pin(self,username,psw): req=urllib2.Request(self.__url) recvdata=urllib2.urlopen(req).read() params={ "action":"submit", "regCallback":"http://api.t.sina.com.cn/oauth/authorize?oauth_token=%s&oauth_callback=none&from=" % self.__oauth_token, "oauth_token":self.__oauth_token, "oauth_callback":"none", "from":"", "userId":username, "passwd":psw, } req=urllib2.Request("http://api.t.sina.com.cn/oauth/authorize",urllib.urlencode(params)) recvdata=urllib2.urlopen(req).read() #获得PIN pin=re.search("<b>.*:[0-9]*<",recvdata).group(0) pin=pin[pin.find("\x9a")+1:-1] return pin def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception, e: print e return ''
def handle(self, *args, **options): print('Start classifying influence area\n') YORO_CONSUMER_KEY = settings.SINA_CONSUMER_KEY YORO_CONSUMER_SECRET = settings.SINA_CONSUMER_SECRET auth = OAuthHandler(YORO_CONSUMER_KEY, YORO_CONSUMER_SECRET) auth.setToken('128021658f2bfdae185d89bdffb3cede','1713185d5c8208e8f1ef27a1f484ebc9') api = API(auth) mid_list = [] rt_count = 0 #Count of status that retweet my status ids_list = [] tried_count = 0 while True: timeline = api.user_timeline(count=200,user_id=1275017594) if len(timeline) == 0: tried_count += 1 #print 'try again in getting timeline' else: break if tried_count > 3: raise Exception('weibo api error. No timeline got') break for line in timeline: text = getAtt(line, 'text') retweet = getAtt(line, 'retweet') if retweet: text += getAtt(retweet, 'text') if is_fashion(text): mid_list.append(str(getAtt(line, "id"))) if len(mid_list) == 20: ids_list.append(','.join(mid_list)) mid_list = [] if mid_list: #append the remaining ids ids_list.append(','.join(mid_list)) for ids in ids_list: counts = api.counts(ids=ids) for obj in counts: rt_count += getAtt(obj, 'rt') sample_size = (len(ids_list)-1)*20 + len(ids_list[-1]) if ids_list else 0 influence_count = long(rt_count * 50 * 3990 * 1.0/(sample_size+1)) #indirect influence influence_count += 3899834 #direct influence print influence_count print('Finished classifying influence area\n')
def get(self): access_token = self.SESSION['oauth_access_token'] auth = OAuthHandler(SINA_CONSUME_KEY, SINA_CONSUME_SECRET) auth.setToken(access_token.key, access_token.secret) me = WeiboAPI(auth).me() u = User() has_sina = u._api.is_sina_exist(unicode(me.id)) if not has_sina: data = {} data['nick'] = me.name data['sina_id'] = unicode(me.id) data['photo'] = unicode(me.profile_image_url) access_token = self.SESSION['oauth_access_token'] data['access_token'] = access_token.key+'&'+access_token.secret u._api.create(**data) u.whois('sina_id', unicode(me.id)) self.set_secure_cookie("user", u.nick.encode('utf-8'), 1) self.SESSION['uid']=u._id return self.redirect('/')
def __init__(self,app_key="3146673438",app_secret="f65a02335629c4ff5c4a5314fedfa97f"): app_key=app_key app_secret=app_secret file=open("token","r") token_key=file.readline() token_secret=file.readline() file.close() auth=OAuthHandler(app_key,app_secret) auth.setToken(token_key[0:-1],token_secret) self.api=API(auth) self.tts=pyTTS.sapi.SynthAndOutput() self.mp=Dispatch("WMPlayer.OCX")## self.count=30 self.chanel="好友频道" self.name_list=[] self.txt_list=[] self.version="1.0" self.firstplay=True '''
def GET(self): auth = OAuthHandler(oauth.APP_KEY, oauth.APP_SECRET) auth.setToken(session.atKey[web.ctx.ip], session.atSec[web.ctx.ip]) api = API(auth) unread = api.unread() timeline = api.mentions() html = '<p>%(id)s. %(user)s created %(created)s: %(text)s -- %(ref)s</p>' h_list = [] for status in timeline: weibo = {} weibo['id'] = status.id weibo['created'] = status.created_at weibo['user'] = status.text weibo['text'] = status.text weibo['source'] = status.source weibo['ref'] = '' refer = getattr(status, 'retweeted_status', None) if refer: weibo['ref'] = u'{[%s]%s}'% (refer.user.name, refer.text) h_list.append(html % weibo) html = ''.join(h_list) return html
@author: leishg ''' from weibopy.api import API from weibopy.auth import OAuthHandler App_Key = "1301184712" App_Secret = "72023ad9cf7e87b163921cc1490c2cef" auth = OAuthHandler(App_Key, App_Secret) auth_url = auth.get_authorization_url() print 'Please authorize: ' + auth_url verifier = raw_input('PIN: ').strip() #http://api.t.sina.com.cn/oauth/authorize?oauth_token=4a72f6e4813750610c47f4c86120d0a2 #496558 access_token = "7e4261f41e53aab3e2f7da5c8ffb3f1b" access_key = "285414" #auth.get_access_token(verifier) auth.setToken("0ae7e293bfabc120c74fc25ab234f028", "77083ac464f82da67f5a7764b9d0088d") api = API(auth) status = api.get_user(id=1650951660) print status #status = api.update_status('³ÇÊлƻè--ºéÆô'.encode("utf-8")) #print status.id #print status.text
if e.errno == errno.EEXIST: pass else: raise buzz_url = 'https://www.googleapis.com/plus/v1/people/' + BUZZ_USERID + '/activities/public?key=' + GOOGLE_API_KEY # 读buzz fp = urlopen(buzz_url) #fp = open('buzz.json') buzz = load(fp) fp.close() # 微博认证 auth = OAuthHandler(WEIBO_APP_KEY, WEIBO_APP_SECRET) auth.setToken(WEIBO_TOKEN_KEY, WEIBO_TOKEN_SECRET) api = API(auth) # 读已经同步过的activity id synced_ids = set() try: fp = open(HISTORY_FILE, 'r') for line in fp: synced_ids.add(line.strip()) fp.close() except IOError, e: # 如果文件不存在,就继续;否则,触发异常 if e.errno != errno.ENOENT: raise
def crawl_video(self): try: sina_key = KeyValue.objects.get(key='CRAWL_SINA_KEY').value sina_secret = KeyValue.objects.get(key='CRAWL_SINA_SECRET').value since_id = KeyValue.objects.get(key='CRAWL_SINA_SINCE_ID').value except: print('Error in getting necessary key-value\n') return #Construct video source from database vss = Video_Source.objects.all() vs_dict = {} for vs in vss: sa = vs.sina_account if sa in vs_dict: vs_dict[sa] = vs_dict[sa].append(vs.channel_id) else: vs_dict[sa] = [vs.channel_id] #print(str(vs_dict)) auth = OAuthHandler(settings.SINA_CONSUMER_KEY, settings.SINA_CONSUMER_SECRET) auth.setToken(sina_key, sina_secret) api = API(auth) count_per_page = 200 page = 1 # Feature: 0:All 1,Original 2:Picture 3:Video 4:Music if since_id: timeline = api.friends_timeline(count=count_per_page, since_id=since_id, page=page, feature=3) else: timeline = api.friends_timeline(count=count_per_page, page=page, feature=3) is_first_obj = True while timeline: #while the list user_timeline is not [] for obj in timeline: try: status_id = self.getAtt(obj, 'id') if is_first_obj: since_id_obj = KeyValue.objects.get(key='CRAWL_SINA_SINCE_ID') since_id_obj.value = status_id since_id_obj.save() is_first_obj = False text = self.getAtt(obj, 'text') friend = self.getAtt(obj, 'user') friend_id = self.getAtt(friend, 'id') #64 int #screen_name = self.getAtt(friend, 'screen_name') snippet = '' retweet = self.getAtt(obj, 'retweeted_status') if retweet: #Discard the original text snippet = text text = self.getAtt(retweet, 'text') date = self.getAtt(obj, "created_at") comments = api.comments(id=status_id) comments_list = [] for comment in comments: comments_list.append(self.getAtt(comment, 'text')) snippet = ' '.join(comments_list) urls = re.findall('http://t.cn/[a-zA-Z0-9]{5,8}', text) #process text before using it as title of item ,strip @ and urls url_index = text.find('http://') text = text[:url_index] text = text.replace(u'【', ' ') text = text.replace(u'】', ' ') for url in urls: #Typically there should only be one parsed = urlparse.urlparse(url) h = httplib.HTTPConnection(parsed.netloc) h.request('HEAD', parsed.path) response = h.getresponse() if response.status / 100 == 3 and response.getheader('Location'): #continue checking redirect url = response.getheader('Location') if not is_video(url): continue msg_or_id = add_item(url, pre_name=text) if isinstance(msg_or_id, int) or isinstance(msg_or_id, long): item = Item.objects.get(pk=msg_or_id) if date: item.create_date = date item.snippet = snippet if friend_id in vs_dict: item.channels = ','.join([str(x) for x in vs_dict[friend_id]]) item.save() except Exception, e: #Tolerate error in importing one weibo continue page += 1 print 'page:' + str(page) if page == 4: break if since_id: timeline = api.friends_timeline(count=count_per_page, since_id=since_id, page=page) else: timeline = api.friends_timeline(count=count_per_page, page=page)
import time import urllib,sys,socket import simplejson as json socket.setdefaulttimeout(5) consumer_key= 'yyy' consumer_secret ='yyy' token = 'xxx' tokenSecret = 'xxx' t_timeline_url = 'https://twitter.com/statuses/user_timeline/yyy.json' twitter_last_id = '0' auth = OAuthHandler(consumer_key, consumer_secret) auth.setToken(token, tokenSecret) api = API(auth) while 1: try: tl_file = urllib.urlopen(t_timeline_url) timeline = json.load(tl_file) if twitter_last_id == '0': twitter_last_id = timeline[0]['id_str'] print 'init twitter_id:' print twitter_last_id if isinstance(timeline,list): tweets_to_be_post = [] for tl in reversed(timeline): if long(tl['id_str']) > long(twitter_last_id): tweets_to_be_post.append({'id_str':tl['id_str'],'text':tl['text']})
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)
class myapi(): def __init__(self, username="******", psw="123456789"): #self.logfile=log_stream.log_stream("sina_sdk") global gconsumer_key global gconsumer_secret global gtoken global gtokenSecret #创建一个opener self.__cJar = cookielib.CookieJar() self.__opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(self.__cJar)) self.__opener.addheaders = [ ('User-agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)') ] urllib2.install_opener(self.__opener) #创建一个auth对象 self.__auth = OAuthHandler(gconsumer_key, gconsumer_secret) self.__auth.setToken(gtoken, gtokenSecret) #创建api对象 self.__api = API(self.__auth) def __del__(self): pass def __get_pin(self, username, psw): req = urllib2.Request(self.__url) recvdata = urllib2.urlopen(req).read() params = { "action": "submit", "regCallback": "http://api.t.sina.com.cn/oauth/authorize?oauth_token=%s&oauth_callback=none&from=" % self.__oauth_token, "oauth_token": self.__oauth_token, "oauth_callback": "none", "from": "", "userId": username, "passwd": psw, } req = urllib2.Request("http://api.t.sina.com.cn/oauth/authorize", urllib.urlencode(params)) recvdata = urllib2.urlopen(req).read() #获得PIN pin = re.search("<b>.*:[0-9]*<", recvdata).group(0) pin = pin[pin.find("\x9a") + 1:-1] return pin def getAtt(self, key): try: return self.obj.__getattribute__(key) except Exception, e: print e return ''
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)
#!/usr/bin/env python # -*- coding: utf-8 -*- from weibopy.auth import OAuthHandler from weibopy.api import API import ConfigParser auth = OAuthHandler('3028524014','660eb5d3feacc40d3bba28e0b9dcc50b') #你的应用的key和secret auth.setToken('d7cf5c4d17156226a80b2b61a51f97d5','79b483a7a80e2a304ee0e227f5a83dc6') #你从新浪获得的令牌token和密码tokensecret api = API(auth) #得到经过认证和授权的、能访问新浪资源的开发界面 #api.updat_status("Hello World") #向你的帐号发一个微博,上新浪微博查看:“Hello World” weibo = api.public_timeline() for i in weibo: print weibo.text
def compute(str_inf_pk): try: inf = Influence.objects.get(pk=str_inf_pk) auth = OAuthHandler(settings.SINA_CONSUMER_KEY, settings.SINA_CONSUMER_SECRET) #auth.setToken(inf.sina_key, inf.sina_secret) auth.setToken('128021658f2bfdae185d89bdffb3cede', '1713185d5c8208e8f1ef27a1f484ebc9') #Calculating for celebrity api = API(auth) followed_dict = {} if inf.follower_count > 1000: #only for popular users that have too many people retweet his status followed, cursors = api.friends(count=200, cursor=-1) while True: for f in followed: followed_dict[getAtt(f, 'screen_name')] = 1 if cursors[1] == 0: break followed, cursors = api.friends(count=200, cursor=cursors[1]) """TODO:This part seems to be unstable;Sometimes it doens work""" #Calculate the most influenced friends through mentions api mentions = api.mentions(count=200) friends_dict = {} friends_image_dict = {} for m in mentions: user = getAtt(m, 'user') screen_name = getAtt(user, 'screen_name') if screen_name in friends_dict: friends_dict[screen_name] += 1 else: if screen_name == inf.screen_name: continue friends_dict[screen_name] = 1 friends_image_dict[screen_name] = getAtt(user, 'profile_image_url') friends = sorted(friends_dict.iteritems(), key=operator.itemgetter(1), reverse=True) if followed_dict: friends_list = [] backup_list = [] for f in friends: if f[0] in followed_dict: friends_list.append(f[0]) else: backup_list.append(f[0]) if len(friends_list) == 4: break friends_list.extend(backup_list[:4-len(friends_list)]) else: friends_list = [f[0] for f in friends[:4]] influence_friends = ','.join(friends_list) if influence_friends: inf.influence_friends = influence_friends friends_images = [friends_image_dict[f] for f in friends_list] else: friends_images = [] #Calculates the quality of followers; Also get average followers count of sampled followers total = 0 active_count = 0 counted = 0 followers, cursors = api.followers(user_id=inf.sina_account, cursor=-1, count=200) while True: #next_cursor is not zero means not the end for f in followers: counted += 1 f_follower_count = getAtt(f, 'followers_count') #f_friends_count = getAtt(f, 'friends_count') f_status_count = getAtt(f, 'statuses_count') if ((f_follower_count > 50 or f_status_count > 50) and f_follower_count + f_status_count > 75 or f_follower_count + f_status_count > 150): active_count += 1 total += f_follower_count break #200 samples should be enough #if cursors[1] == 0: # break #followers, cursors = api.followers(user_id=inf.sina_account, cursor=cursors[1], count=200) avg_follower_of_followers = total*1.0/counted if counted !=0 else 0 active_follower_ratio = active_count * 1.0 /counted if counted !=0 else 0 inf.active_follower_count = int(math.ceil(active_follower_ratio*inf.follower_count)) #Calculates the average rt_count of each tweet based on 200 samples mid_list = [] rt_count = 0 #Count of status that retweet my status ids_list = [] timeline = api.user_timeline(user_id=inf.sina_account, count=200) for line in timeline: mid_list.append(str(getAtt(line, "id"))) if len(mid_list) == 20: ids_list.append(','.join(mid_list)) mid_list = [] if mid_list: #append the remaining ids ids_list.append(','.join(mid_list)) if inf.status_count > 0 and not ids_list: raise Exception('weibo api fails') for ids in ids_list: counts = api.counts(ids=ids) for obj in counts: rt_count += getAtt(obj, 'rt') sample_size = (len(ids_list)-1)*20 + len(ids_list[-1]) if ids_list else 0 average_rt_count = rt_count*1.0/sample_size if sample_size != 0 else 0 inf.average_rt_count = average_rt_count influence_count = long(average_rt_count * inf.status_count * avg_follower_of_followers) influence_count += inf.status_count * inf.follower_count #plus this so that it won't be zero inf.influence_count = influence_count magic_constant = 4.07 #99/math.log(36613694013) for YangMi inf.influence_score = magic_constant * math.log(inf.influence_count+0.1) if inf.influence_count > 0 else 0 inf.influence_score = int(math.ceil(math.sqrt(inf.influence_score)*10)) #To make the score larger if inf.influence_score > 99: inf.influence_score = 99 print inf.influence_count if inf.influence_count > 250000000: #To avoid huge number exceeding the number of users on weibo inf.influence_count = 250000000 + long(random.random()*1000000) #img_url = settings.MEDIA_URL + 'apps/influence/sample.gif' """TODO: check whether the profile is complete; But this may be not necessary""" inf.last_use_date = datetime.now() inf.error = 'success' #Erase the error message last time inf.save() except Exception, e: try: inf.error = str(e) inf.save() except: pass print str(e)
app_secret = '616611de12d73ba6769e7967e03356b6' #vmonit #access_token_key = '4263fa4f1ab9c655ff2adaf53efb4a15' #acces_token_secret = '7b3994d665882c6fe16bc2453217867a' #videomonit access_token_key = '0d51053f97027a7f4651e36071120615' acces_token_secret = '614a6ec600bfdcb6d29728e120ebda73' auth = OAuthHandler(app_key, app_secret) #url = auth.get_authorization_url() #webbrowser.open(url) #verifier = raw_input("PIN:").strip() #token = auth.get_access_token(verifier) #print token.key, " ", token.secret auth.setToken(access_token_key, acces_token_secret) api = API(auth) text_list = [" 我家的摄像头正在摄像"," 看看我家楼下的车,我家的摄像头正在拍摄"," 测试中,我家的摄像头正在拍摄", " 过段时间把它移到室内,出门开始监控,我家的摄像头正在拍摄","..,我家的摄像头正在摄像", " 共享摄像头,我家的摄像头正在拍摄"," 我是一个摄像头,我没有在偷拍哦!", "难道我会告诉你我在偷看吗?"] def ShareSnapToWeibo(now_time): try: second = int(time.strftime('%S', now_time)) file_name = 'snapshots/'+time.strftime('%Y-%m-%d %H-%M-%S', now_time) + '-image.png' status_text = time.strftime('%Y年%m月%d日 %H点%M分%S秒', now_time)+ text_list[second % 7] status = api.upload(file_name, status_text, lat='12.3', long='45.6')#text_list[second % 6]) print "Share Success" except Exception as e: print "Share Error:%s" % e return if __name__ == '__main__': api.update_status("test")
# 有了授权码verifier之后,加上之前缓存在Session中的rtKey和rtSecret便可获取用户令牌密钥。 #设定请求令牌密钥(桌面应用跳过此句) auth.set_request_token( rtKey, rtSecret ); #获取用户令牌密钥. access_token = auth.get_access_token( verifier ); atKey = access_token.key; atSecret = access_token.secret; # 终于,我们获取到了用户令牌密钥atKey和atSecret,接下来的所有步骤都需要用这两个参数来验证用户的身份。 # 三、获取用户信息 from weibopy.error import WeibopError; #设定用户令牌密钥. auth.setToken( atKey, atSecret ); #绑定用户验证信息. api = API(auth); #获取用户信息. try: user = api.verify_credentials(); except WeibopError, e: return e.reason; #用户ID userid = user.id; #用户昵称. username = user.screen_name.encode('utf-8'); # 四、发布微博消息 from weibopy.error import WeibopError;
def classify_influence(inf_id, other=False): """ TODO: 1, Calculate the most popular tags, so that we can assign idf score 2, Accumulate more meaningful tags """ inf_id = inf_id.decode('gbk') print inf_id.encode('gbk') try: inf_id = int(inf_id) inf = Influence.objects.get(pk=inf_id) except: inf, created = Influence.objects.get_or_create(screen_name=inf_id) if created: auth = OAuthHandler(settings.SINA_CONSUMER_KEY, settings.SINA_CONSUMER_SECRET) auth.setToken('128021658f2bfdae185d89bdffb3cede','1713185d5c8208e8f1ef27a1f484ebc9') api = API(auth) user = api.get_user(screen_name=inf_id) inf.sina_account = getAtt(user, 'id') inf.verified = getAtt(user,'verified') inf.screen_name = getAtt(user, 'screen_name') inf.description = getAtt(user, 'description') inf.follower_count = getAtt(user, 'followers_count') inf.following_count = getAtt(user, 'friends_count') inf.status_count = getAtt(user, 'statuses_count') inf.favourites_count = getAtt(user, 'favourites_count') inf.create_date = getAtt(user, 'created_at') inf.save() auth = OAuthHandler(settings.SINA_CONSUMER_KEY, settings.SINA_CONSUMER_SECRET) if other: auth.setToken('128021658f2bfdae185d89bdffb3cede', '1713185d5c8208e8f1ef27a1f484ebc9') else: auth.setToken(inf.sina_key, inf.sina_secret) api = API(auth) mmseg.dict_load_defaults() """Put this in db first""" candidate_tags = KeyValue.objects.get(key='CANDIDATE_TAGS') area_dict = {} # id_list = api.followers_ids(user_id=inf.sina_account, count=100) #default to 500, maximum is 5000; This consumes a lot of api limit # ids = id_list[0].ids #Weird that getAtt won't work # for id in ids: # tags = api.tags(user_id=id) #user_id is required! # tag_list = [] # for tag in tags: # tag_list.append(getAtt(tag, 'value').lower().encode('utf-8')) # mmseg_text = mmseg.Algorithm(' '.join(tag_list)) # for token in mmseg_text: # try: # term = token.text.decode('utf-8').lower() # #next_term = mmseg_text[i+1].text.decode('utf-8') if i < len_list - 1 else '' # except: # continue # train_value = area_train_data.get(term, None) # #if not train_value: # # train_value = area_train_data.get(term + next_term, None) # if train_value: # print 'in dict' # for index in train_value: # if index in area_dict: # area_dict[index] += 1 # else: # area_dict[index] = 1 # else: # candidate_tags.value += ' ' + term candidate_tags.save() area_distr_dict = {} mid_list = [] ids_list = [] tweet_list = [] #Store the text of tweet and retweet rt_count_list = [] tried_count = 0 while True: timeline = api.user_timeline(user_id=inf.sina_account, count=200) if len(timeline) == 0 and inf.status_count >0: tried_count += 1 print 'try again in getting timeline' else: break if tried_count > 3: raise Exception('weibo api error. No timeline got') break for line in timeline: text = getAtt(line, 'text') retweet = getAtt(line, 'retweeted_status') retweet_text = getAtt(retweet, 'text') if retweet_text: text += retweet_text tweet_list.append(text) mid_list.append(str(getAtt(line, "id"))) if len(mid_list) == 20: ids_list.append(','.join(mid_list)) mid_list = [] if mid_list: #append the remaining ids ids_list.append(','.join(mid_list)) if inf.status_count > 0 and not ids_list: raise Exception('weibo api fails') tweet_list_correct = [] correct_index = 20 for ids in ids_list: counts = api.counts(ids=ids) if len(counts) == 0: print 'error in counts!' correct_index += 20 continue for obj in counts: rt_count_list.append(getAtt(obj, 'rt')) tweet_list_correct.extend(tweet_list[correct_index-20:correct_index]) correct_index += 20 if len(tweet_list_correct) == 0 or len(tweet_list_correct) != len(rt_count_list): raise Exception('weibo api fails') print 'length of tweet list and rt_count list', len(tweet_list_correct), len(rt_count_list) #Remedy for those user who has posted less than 200 status amplify_ratio = 1.0 if len(tweet_list_correct) == 200 else 200.0/len(tweet_list_correct) for i in range(len(tweet_list_correct)): print i #This number 100 should be replaced by avg_follower_count #Use math.sqrt to boost those tweet that has not been retweeted, #and smooth the effect of famous people tweeting about things not related to them added_count = (rt_count_list[i]*100 + math.sqrt(inf.follower_count)) * amplify_ratio assigned_area = {} try: #In Unix environment from sinal import signal, SIGALRM, alarm #@UnresolvedImport def handler(signum, frame): #print 'Signal handler called with signal', signum raise Exception("This code block runs for too long time!") signal(SIGALRM, handler) alarm(3) mmseg_text = mmseg.Algorithm(tweet_list_correct[i].encode('utf-8')) alarm(0) #cancel the alarm after finised except ImportError: # In windows, SIGALRM, alarm is not available in signal module mmseg_text = mmseg.Algorithm(tweet_list_correct[i].encode('utf-8')) except: #mmseg halts for too long, process next tweet continue for token in mmseg_text: try: term = token.text.decode('utf-8').lower() except: continue train_value = area_train_data.get(term, None) if train_value: print 'in dict' for index in train_value: if index not in assigned_area: #This tweet has already been assigned to one area if index in area_dict: area_dict[index] += added_count else: area_dict[index] = added_count assigned_area[index] = True if index in area_distr_dict: area_distr_dict[index] += 1 else: area_distr_dict[index] = 1 else: area_distr_dict[index] += 1 candidate_tags.save() sorted_tuple = sorted(area_dict.iteritems(), key=operator.itemgetter(1), reverse=True) if inf.follower_count > 100000: for i in range(1,len(sorted_tuple)): #Only normalize on secondary influence areas and belows index = sorted_tuple[i][0] model_follower_count = areas[index][4] if inf.follower_count > model_follower_count: area_dict[index] = area_dict[index]*1.0/inf.follower_count*model_follower_count num_areas = len(area_distr_dict) total_keyword_count = 0 for index in area_distr_dict: total_keyword_count += area_distr_dict[index] for k in area_dict: area_distr_ratio = num_areas * area_distr_dict[k]*1.0/total_keyword_count print k , area_distr_ratio, area_distr_dict[k] area_dict[k] = 100.0/math.log(areas[k][3]) * math.log(area_dict[k]*area_distr_ratio) if area_dict[k] > 100: area_dict[k] = 100.0 sorted_tuple = sorted(area_dict.iteritems(), key=operator.itemgetter(1), reverse=True) for st in sorted_tuple: print areas[st[0]][1].encode('gbk'), st[1]