Example #1
0
 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>')
Example #2
0
 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>')
Example #3
0
    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'])
Example #4
0
 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"))
Example #5
0
 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
Example #6
0
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')
Example #7
0
def on_post_was_submit(sender,post,*args,**kwargs):
    try:
        from blog.models import OptionSet
        bind = OptionSet.get('bind_weibo','')=='True'
        if bind:
            access_token_key = OptionSet.get('weibo_access_token_key','')
            access_token_secret = OptionSet.get('weibo_access_token_secret','')
            weibo_client.setToken(access_token_key,access_token_secret)
            from weibopy.api import API
            from django.template.defaultfilters import removetags
            api = API(weibo_client)
            api.update_status(status='[%s] %s ... %s'\
                              %(post.title,removetags(post.content[:60],'a p span div img br'),\
                                settings.BLOG_DOMAIN+post.get_absolute_url()))
    except:
        pass
Example #8
0
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) 
Example #9
0
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')
Example #10
0
def on_post_was_submit(sender, post, *args, **kwargs):
    try:
        from blog.models import OptionSet
        bind = OptionSet.get('bind_weibo', '') == 'True'
        if bind:
            access_token_key = OptionSet.get('weibo_access_token_key', '')
            access_token_secret = OptionSet.get('weibo_access_token_secret',
                                                '')
            weibo_client.setToken(access_token_key, access_token_secret)
            from weibopy.api import API
            from django.template.defaultfilters import removetags
            api = API(weibo_client)
            api.update_status(status='[%s] %s ... %s'\
                              %(post.title,removetags(post.content[:60],'a p span div img br'),\
                                settings.BLOG_DOMAIN+post.get_absolute_url()))
    except:
        pass
Example #11
0
def test_rp(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:
            username = api.me().screen_name
            number = int(md5.md5(username.encode('utf-8')).hexdigest(), 16)
            rp = number % 100
            rating = rp2rating(rp)
            api.update_status(u"%s, 你的人品是 %d, %s" % (username, rp, rating))
            success = u"成功发布"
        except:
            raise
            success = u"失败"
        return HttpResponseRedirect('/status')
    return HttpResponseRedirect('/status')
Example #12
0
    def post(self):
        t_name = self.request.get('t_name')
        s_name = self.request.get('s_name')
        s_request_key = self.request.get('s_request_key')
        s_request_secret = self.request.get('s_request_secret')
        t_request_key = self.request.get('t_request_key')
        t_request_secret = self.request.get('t_request_secret')
        t_pin = self.request.get('t_pin')
        s_pin = self.request.get('s_pin')
        self.response.out.write("""<html><head><title>Tui2Lang-Result</title></head><body><center>""")
        if t_name == "" or s_name =="" or s_pin == "":
            self.response.out.write("""<h2>4 Input can not be empty! <a href="/">Back</a></h2>""")
        else:
            sina = OAuthHandler(app_key,app_secret)
            sina.set_request_token(s_request_key,s_request_secret)
            s_access_token = sina.get_access_token(s_pin.strip())
            sina_api = API(sina)

            twitter = tweepy.OAuthHandler(consumer_key,consumer_secret)
            twitter.set_request_token(t_request_key,t_request_secret)
            t_access_token = twitter.get_access_token(t_pin.strip())
            twitter_api = tweepy.API(twitter);
            
            t_tl = twitter_api.user_timeline()
            t_last_id = t_tl[0].id_str
            t_last_text = replace_tweet(t_tl[0].text)
            

            oauth_user = OauthUser(key_name=s_name)
            oauth_user.twitter_name = t_name
            oauth_user.sina_name = s_name
            oauth_user.sina_access_key = s_access_token.key
            oauth_user.sina_access_secret = s_access_token.secret
            oauth_user.twitter_access_key = t_access_token.key
            oauth_user.twitter_access_secret = t_access_token.secret
            oauth_user.twitter_last_id = t_last_id
            oauth_user.put()

            try:
                sina_api.update_status(t_last_text)            
            except WeibopError,e:
                self.response.out.write(e)
            else:
Example #13
0
class Weibo:
    def __init__(self):
        #设定网页应用回调页面(桌面应用设定此变量为空)
        BACK_URL = ""
        #验证开发者密钥.
        auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL)
        #设定用户令牌密钥.
        auth.setToken(TOKEN_KEY, TOKEN_SECRET)
        #绑定用户验证信息.
        self.api = API(auth)

    def send(self, message, image_path=None):
        try:
            if image_path:
                self.api.upload(image_path, message)
            else:
                self.api.update_status(message)
        except WeibopError, e:
            print e.reason
Example #14
0
def test_rp(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:
            username = api.me().screen_name
            number = int(md5.md5(username.encode('utf-8')).hexdigest(), 16)
            rp = number % 100
            rating = rp2rating(rp)
            api.update_status(u"%s, 你的人品是 %d, %s" %(username, rp, rating))
            success = u"成功发布"
        except:
            raise
            success = u"失败"
        return HttpResponseRedirect('/status')
    return HttpResponseRedirect('/status')
Example #15
0
class Weibo:
    def __init__(self):
        # 设定网页应用回调页面(桌面应用设定此变量为空)
        BACK_URL = ""
        # 验证开发者密钥.
        auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL)
        # 设定用户令牌密钥.
        auth.setToken(TOKEN_KEY, TOKEN_SECRET)
        # 绑定用户验证信息.
        self.api = API(auth)

    def send(self, message, image_path=None):
        try:
            if image_path:
                self.api.upload(image_path, message)
            else:
                self.api.update_status(message)
        except WeibopError, e:
            print e.reason
Example #16
0
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)
Example #17
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 '你又在微博上跟大家说了一句话~~'
Example #18
0
    def get(self):
        query = db.GqlQuery("SELECT * FROM OauthUser")
        if query.count() > 0:
            for result in query:
                # rebuild twitter api
                twitter = tweepy.OAuthHandler(consumer_key,consumer_secret)
                twitter.set_access_token(result.twitter_access_key,result.twitter_access_secret)
                twitter_api = tweepy.API(twitter)
                
                timeline = twitter_api.user_timeline()
                last_id = result.twitter_last_id
                tweets_to_be_post = []
                for tl in timeline:
		    # disable jiepang
                    if int(tl.id_str) > int(last_id):
			if tl.source.find(unicode('街旁(JiePang)','utf8')) == -1  and tl.source.find('Instagram') == -1:
			    tweets_to_be_post.append({'id_str':tl.id_str,'text':tl.text})
                    else:
                        break
                if len(tweets_to_be_post) > 0:
                    # rebuild sina api
                    sina = OAuthHandler(app_key,app_secret)
                    sina.set_access_token(result.sina_access_key,result.sina_access_secret)
                    sina_api = API(sina)
                    
                    for tweet_obj in reversed(tweets_to_be_post):
                        user = OauthUser.get_by_key_name(result.sina_name)
                        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)
			self.response.out.write(tweet)
                        try:
                            sina_api.update_status(tweet)
                            user.twitter_last_id = cur_id
                            user.put()
                            self.response.out.write('同步成功!')
                        except WeibopError,e:
                            self.response.out.write(e)
                            self.response.out.write('<br>')
Example #19
0
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()
Example #20
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]
Example #21
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]
Example #22
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 '你又在微博上跟大家说了一句话~~'
Example #23
0
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)
Example #24
0
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)
Example #25
0
 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'])
Example #26
0
 def sinaapp(self,app_key,app_secret):
         auth = OAuthHandler(app_key, app_secret)  ##认证
         auth_url = auth.get_authorization_url()    ##返回授权页面链接,用浏览器打开
         #webbrowser.open(auth_url)
         content = self._request(auth_url)[1].read()        
         soup=BeautifulSoup.BeautifulSoup(''.join(content))
         #print content
         pin=soup.span.string   #自动获取pin码
         #print 'Please authorize: ' + auth_url  ##输入获得的Pin码
         #verifier = raw_input('输入您在浏览器页面显示的PIN码: ').strip()
         auth.get_access_token(pin)
         api = API(auth)  #整合函数
         connent=raw_input('What are you want to say?')
         status = api.update_status(status=connent)#发布微博
         print "Send Successed"
         raw_input('Press enter to exit ......')
Example #27
0
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 getAttValue(self, obj, key):
        try:
            return obj.__getattribute__(key)
        except Exception as e:
            print(e)
            return ''
        
    def basicAuth(self, source, username, password):
        self.authType = 'basicauth'
        self.auth = BasicAuthHandler(username, password)
        self.api = API(self.auth,source=source)
    
    def update(self, message):
        status = self.api.update_status(message)
        self.obj = status
        id = self.getAtt("id")
        text = self.getAtt("text")
        print("update---"+ str(id) +":"+ 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)
Example #28
0
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 update(self, message):
        status = self.api.update_status(lat='39', long='110', status=message)
        self.obj = status
        id = self.getAtt("id")
        text = self.getAtt("text")
        print("update---" + str(id) + ":" + 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)
Example #29
0
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 update(self, message):
        status = self.api.update_status(lat='39', long='110', status=message)
        self.obj = status
        id = self.getAtt("id")
        text = self.getAtt("text")
        print("update---"+ str(id) +":"+ 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)
Example #30
0
#用户昵称.
username = user.screen_name.encode('utf-8');
# 四、发布微博消息
from weibopy.error import WeibopError;

#设定用户令牌密钥.
auth.setToken( atKey, atSecret );
#绑定用户验证信息.
api = API(auth);

#如果不传送图片.
if ( ImagePath == None ):
  #发布普通微博.
  try:
    #message为微博消息,lat为纬度,long为经度.
    api.update_status( message, lat, long );
  except WeibopError, e:
    return e.reason;

#如果传送图片.
else:
  #发布图文微博.
  try:
    #ImagePath为图片在操作系统中的访问地址,其余同上.
    api.upload( ImagePath, message, lat, long );
  except WeibopError, e:
    return e.reason;
# 五、获取微博消息列表
#设定用户令牌密钥.
auth.setToken( atKey, atSecret );
#绑定用户验证信息.
Example #31
0
class MyWeibo:
    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
        '''
        tune=self.mp.newMedia("1.wav")
        self.mp.currentPlaylist.appendItem(tune)
        tune=self.mp.newMedia("2.mp3")
        self.mp.currentPlaylist.appendItem(tune)
        tune=self.mp.newMedia("3.mp3")
        self.mp.currentPlaylist.appendItem(tune)
        '''
    def __del__(self):
        self.deleteFiles()
        
    def mute(self,flag):
        self.mp.settings.mute=flag
        
    def play(self):##
        if self.firstplay:
            self.firstplay=False
            self.listen_to(self.chanel,n=self.count)
            return True
        if self.mp.controls.isAvailable("play")==False:
            return False
        self.mp.controls.play()
        return True
    
    def prev(self):
        if self.mp.controls.isAvailable("previous")==False:
            return False
        self.mp.controls.previous()
        return True
    
    def next(self):
        if self.mp.controls.isAvailable("next")==False:
            return False
        self.mp.controls.next()
        return True
    
    def pause(self):
        if self.mp.controls.isAvailable("pause")==False:
            return False
        self.mp.controls.pause()
        return True
            
    def stop(self):
        if self.mp.controls.isAvailable("stop")==False:
            return False
        self.mp.controls.stop()
        return True
    
    def faweibo(self,message):
        message = message.encode("utf-8")
        try:
            self.api.update_status(status=message)
        except:
            return False
        else:
            return True
    '''
    def update_profile_image (self, filename):#上传图片
        filename=filename.encode("utf-8")
        self.api.update_profile_image(code(filename))'''
    def upload(self, filename, message):#上传
        message = message.encode("utf-8")
        try:
            self.api.upload(filename, status=message)
        except  Exception, e:
            print e
            return False
        else:
Example #32
0
	fout = codecs.open("jlsample.txt", "w", "utf-8")
except IOError:
	print "preseg.txt could not be opened"
	sys.exit(1)

for out in s: 
	print >> fout, out.text

fout.close()	
fp.close()


#############


status = api.update_status(status='hello world', lat='12.3', long='45.6') 
print status.id
print status.text

angies = api.search_users("Angie Zhu")
angie1 = angies[0]
ch = angie1.screen_name
print ch.encode("utf8")

weibos = api.public_timeline()
for weibo in weibos:
    print weibo.text.encode('utf8')

user = api.get_user('brothercutter')
print user.screen_name
print user.followers_count #打印粉丝数
Example #33
0
        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']})
            if len(tweets_to_be_post) > 0:
                for tweet_obj in tweets_to_be_post:
                    cur_id = tweet_obj['id_str']
                    cur_tweet = tweet_obj['text']
                    twitter_last_id = cur_id
                    print twitter_last_id
                    if cur_tweet.startswith('@'):
                        continue
                    if cur_tweet.count('http://t.co') > 0:
                        for segment in cur_tweet.split():
                            if segment.startswith('http://t.co'):
                                realresponse = urllib.urlopen(segment)
                                if realresponse.getcode() == 200:
                                    cur_tweet = cur_tweet.replace(segment,realresponse.geturl())
                    api.update_status(cur_tweet)
    except Exception as tui2lang:
        print time.ctime()
        print tui2lang
    time.sleep(90)
def update_weibo(gruser, message):
    access_token = OAuthAccessToken.all().filter("specifier = ",gruser.username).fetch(1)[0]
    auth_client = _oauth()
    auth_client.setToken(access_token.oauth_token, access_token.oauth_token_secret)
    api = API(auth_client, source = "Reader2微博")
    api.update_status(message)
Example #35
0
#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")