• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python twython.Twython类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twython.Twython的典型用法代码示例。如果您正苦于以下问题:Python Twython类的具体用法?Python Twython怎么用?Python Twython使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Twython类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: getDescriptions

def getDescriptions(credentials_list, users_data, directory):
	
	if len(users_data) is 0:
		print('Complete')
		return 

	
	
	for credential in credentials_list:

		users = users_data[0:100]

		credentials = Twython(app_key=credential[0],
		    	app_secret=credential[1],
		    	oauth_token=credential[2],
		    	oauth_token_secret=credential[3], oauth_version=1)

		data = credentials.lookup_user(screen_name = users)

		for dat in data:
			profile = dat
			handle = str(profile['id'])
			time_zone = str(profile['time_zone'])
			screen_name = profile['screen_name']
	        #utc_offset = profile['utc_offset']
			description = profile['description'].replace("\t", " ")

			with codecs.open(directory[:-4] + "_IDs.csv", 'a', encoding='utf-8') as out:
				out.write(u''+ screen_name + '\t' + handle +'\n')



		users_data = users_data[101:]
		
	getDescriptions(credentials_list, users_data, directory)
开发者ID:jpriniski,项目名称:TwitterGatekeeping,代码行数:35,代码来源:getDescriptions.py


示例2: Sufbot

class Sufbot(object):
    def __init__(self, argDict=None):
        if not argDict:
            argDict = {"force": False, 'stream': False}
            # update this object's internal dict with the dict of args that was passed
            # in so we can access those values as attributes.   
        self.__dict__.update(argDict)
        self.tweet = ""
        self.settings = defaultConfigDict
        s = self.settings
        self.twitter = Twython(s['appKey'], s['appSecret'], s['accessToken'], s['accessTokenSecret'])
         
         
    def SendTweets(self):
        ''' send each of the status updates that are collected in self.tweets 
        '''
        self.twitter.update_status(status=self.tweet)
            
    def Run(self):
        self.GetLyric()
        self.SendTweets()
         
    def GetLyric(self):
        sufjanList = sufbotLyrics.processArtist("http://www.lyricsmode.com/lyrics/s/sufjan_stevens/")
        charcount = 141
        while charcount>140: # ensure tweet is 140 characters or less (twitter character limit)
            lyrics = sufbotLyrics.getRandomLyrics(sufjanList)
            charcount = 0
            for l in lyrics:
                charcount+=len(l)
        tweet = ""
        for l in lyrics:
            tweet+=l+"\n"
        self.tweet = tweet
开发者ID:katekenneally,项目名称:sufbotstevens,代码行数:34,代码来源:sufbot.py


示例3: generate

def generate(request):
    context = RequestContext(request)

    if request.method == 'POST':
        form = BotTokenForm(request.POST)

        if form.is_valid():
            global yellow
            yellow = Bot.objects.get(id=request.POST.get('user'))
            twitter = Twython(settings.API, settings.API_SECRET)

            # Request an authorization url to send the user to...
            callback_url = request.build_absolute_uri(reverse('grabber.views.thanks'))
            auth_props = twitter.get_authentication_tokens(callback_url)

            # Then send them over there, durh.
            request.session['request_token'] = auth_props
            return HttpResponseRedirect(auth_props['auth_url'])


        else:
            print form.errors
    else:
        form = BotTokenForm()
    return render_to_response('grabber/generate.html',{'form': form}, context)
开发者ID:benkul,项目名称:twitterproject,代码行数:25,代码来源:views.py


示例4: thanks

def thanks(request, redirect_url=settings.LOGIN_REDIRECT_URL):
    """A user gets redirected here after hitting Twitter and authorizing your app to use their data.

    This is the view that stores the tokens you want
    for querying data. Pay attention to this.

    """
    # Now that we've got the magic tokens back from Twitter, we need to exchange
    # for permanent ones and store them...
    oauth_token = request.session['request_token']['oauth_token']
    oauth_token_secret = request.session['request_token']['oauth_token_secret']
    twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET,
                      oauth_token, oauth_token_secret)

    # Retrieve the tokens we want...
    authorized_tokens = twitter.get_authorized_tokens(request.GET['oauth_verifier'])

    # If they already exist, grab them, login and redirect to a page displaying stuff.
    try:
        user = User.objects.get(username=authorized_tokens['screen_name'])
    except User.DoesNotExist:
        # We mock a creation here; no email, password is just the token, etc.
        user = User.objects.create_user(authorized_tokens['screen_name'], "[email protected]", authorized_tokens['oauth_token_secret'])
        profile = TwitterProfile()
        profile.user = user
        profile.oauth_token = authorized_tokens['oauth_token']
        profile.oauth_secret = authorized_tokens['oauth_token_secret']
        profile.save()

    user = authenticate(
        username=authorized_tokens['screen_name'],
        password=authorized_tokens['oauth_token_secret']
    )
    login(request, user)
    return HttpResponseRedirect(redirect_url)
开发者ID:Mondego,项目名称:pyreco,代码行数:35,代码来源:allPythonContent.py


示例5: perform_import

    def perform_import(self, retrieval_param, course_code):

        # Setup Twitter API Keys
        app_key = os.environ.get("TWITTER_APP_KEY")
        app_secret = os.environ.get("TWITTER_APP_SECRET")
        oauth_token = os.environ.get("TWITTER_OAUTH_TOKEN")
        oauth_token_secret = os.environ.get("TWITTER_OAUTH_TOKEN_SECRET")

        twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)

        count = 0
        next_max_id = None
        results = None
        while True:
            try:
                if count==0:
                    results = twitter.search(q=retrieval_param,count=100, result_type='mixed')
                else:
                    results = twitter.search(q=retrieval_param,count=100,max_id=next_max_id, result_type='mixed')

                for tweet in results['statuses']:
                    self.insert_tweet(tweet, course_code)

                if 'next_results' not in results['search_metadata']:
                        break
                else:
                    next_results_url_params    = results['search_metadata']['next_results']
                    next_max_id = next_results_url_params.split('max_id=')[1].split('&')[0]
                count += 1
            except KeyError:
                    # When there are no more pages (['paging']['next']), break from the
                    # loop and end the script.
                    break
开发者ID:zwaters,项目名称:CLAtoolkit,代码行数:33,代码来源:cladi_plugin.py


示例6: get

    def get(self):
        tweets = Tweet.query.order_by(Tweet.tweetId.asc()).limit(1).all()
        oldest = tweets[0] if len(tweets) > 0 else None
        twitter = Twython(s.CONSUMER_KEY, s.CONSUMER_SECRET, 
                          s.ACCESS_TOKEN, s.ACCESS_TOKEN_SECRET)
        data = []
        try:
            if oldest:
                logging.info('\n\nOldest tweetId = {0}\n\n'.format(oldest.tweetId))
                data = twitter.get_home_timeline(count=50, max_id=oldest.tweetId)
            else:
                data = twitter.get_home_timeline(count=200)
        except TwythonError as e:
            logging.error('{0}'.format(e))
        else:
            logging.info(str(data))
            for tweet in data:
                if len(tweet.get('entities').get('urls')) > 0:
                    logging.info("\n\nFound urls!\n\n")
                    process_link(tweet, s.USER_ID)
                else:
                    logging.info("\n\nNo urls :(\n\n")

                
            return "OK"
开发者ID:c11z,项目名称:sqrl-server,代码行数:25,代码来源:api.py


示例7: search_twitter

def search_twitter(search_term, geocode=None):
    twitter = Twython(ckey, csecret)
    if geocode:
        result_search = twitter.search(q=search_term, geocode=geocode)
    else:
        result_search = twitter.search(q=search_term)
    return result_search
开发者ID:gvsdan,项目名称:Webdev-test,代码行数:7,代码来源:views.py


示例8: tweet_tap_update

def tweet_tap_update(beer, previous_beer=None):
    twitter = Twython(
        TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET,
        TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET
    )
    # tweet about the beer that used to be on tap
    if previous_beer:
        tweet = u'Blown keg at {0}: {1}, {2} from {3} in {4}, is gone'.format(
            previous_beer['location'].decode('utf-8'), previous_beer['name'].decode('utf-8'),
            INFLECTION.a(previous_beer['style'].decode('utf-8')),
            previous_beer['brewery'].decode('utf-8'), previous_beer['city'].decode('utf-8')
        )
        tweet = check_tweet(tweet)

        if DRY_RUN:
            print 'Would Tweet: ' + tweet
        else:
            twitter.update_status(status=tweet)

    # tweet about the new beer on tap
    tweet = u'Now on tap at {0}: {1}, {2} from {3} in {4}'.format(
        beer['location'].decode('utf-8'), beer['name'].decode('utf-8'),
        INFLECTION.a(beer['style'].decode('utf-8')),
        beer['brewery'].decode('utf-8'), beer['city'].decode('utf-8')
    )
    tweet = check_tweet(tweet)
    
    if DRY_RUN:
        print 'Would Tweet: ' + tweet
    else:
        twitter.update_status(status=tweet)
开发者ID:ryanpitts,项目名称:growlerbot,代码行数:31,代码来源:fetch_taps.py


示例9: twitter_search

def twitter_search(twitter_id, index = 0):

	APP_KEY = APP_KEYS[index]
	APP_SECRET = APP_SECRETS[index]
	OAUTH_TOKEN = OAUTH_TOKENS[index]
	OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index]
	
	twitter =  Twython (APP_KEY, APP_SECRET)
	
	auth = twitter.get_authentication_tokens()
	
    #OAUTH_TOKEN = auth['oauth_token']
    #OAUTH_TOKEN_SECRET = auth['oauth_token_secret']

    
    #print OAUTH_TOKEN
	twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) 
    #ACCESS_TOKEN = twitter.obtain_access_token()
	
    #print twitter.verify_credentials()
	#ACCESS_TOKEN = '701759705421639681-nutlNGruF7WZjq0kXZUTcKVbrnXs3vD'
    #twitter = Twython(APP_KEY, access_token = ACCESS_TOKEN)
	
	response = twitter.get_user_timeline(screen_name = twitter_id)
    # gets 20 results, by default

	L = []
	for r in response:
		d = {} 
		d['text'] = r['text']
		d['screenname'] = r['user']['screen_name']
		d['date'] = r['created_at']
		L.append(d)
	return L
开发者ID:koprty,项目名称:REU_scripts,代码行数:34,代码来源:twitter.py


示例10: TweetThread

class TweetThread(threading.Thread):

    def __init__(self,message):
        super(TweetThread,self).__init__()
        self.message = message
        self.twitter = Twython(
            #consumer key
            "fF86BdSdopE9FAES5UNgPw",
            #consumer secret
            "n7G4K80kYQ6NDMQiYn3GY5Hyk82fF2So17Nl1UQdGWE",
            #access_token
            "1336977176-4CgpPJnJBx7kCRqnwLcRbXI3nLpHj44sp3r2bXy",
            #access_token_secret
            "5rLNvZm3JZdkx0K1Jx9jgsqMG6MmGLAQmPdJ7ChtzA",
        )

    def run(self):
        #send a picture tweet
        print("sending a tweet with an image...")
        photo = open('mugshot.jpg', 'rb')
        try:
            self.twitter.update_status_with_media(media=photo, status=self.message)
            print("sent")
        except:
            print("twython problem")
开发者ID:mattvenn,项目名称:the-waggler,代码行数:25,代码来源:twitter.py


示例11: run

  def run(self):
    pp = pprint.PrettyPrinter(depth=6)

    api = Twython(app_key=options.consumer_key,
                  app_secret=options.consumer_secret,
                  oauth_token=options.access_token_key,
                  oauth_token_secret=options.access_token_secret)

    #do_simulate = True
    do_simulate = False
  
    current_user = { 'id_str' : '1041065317' }
    if not do_simulate:
      current_user = api.verifyCredentials()
      pp.pprint(current_user)

    fortuneComposer = FortuneComposer()
    followController = follow.FollowController([ follow.FollowComposer(current_user) ], current_user=current_user)
    retweetController = retweet.RetweetController([ retweet.RetweetComposer() ], current_user=current_user)
    replyController = reply.ReplyController([ fortuneComposer ], current_user=current_user)
    postController = post.PostController([ fortuneComposer ], current_user=current_user)
    default_time_to_sleep = 1
    if do_simulate:
      default_time_to_sleep = 1
 
    user_stream = stream.Stream(api, 
                                { 'endpoint' : 'https://userstream.twitter.com/1.1/user.json', 'track' : 'bucketobytes' }, 
                                [ followController, retweetController, replyController, postController ],
                                default_time_to_sleep,
                                do_simulate)

    user_stream.connectStream()
开发者ID:MeExplain,项目名称:bucketobytes,代码行数:32,代码来源:bot.py


示例12: get_tweets

def get_tweets(keyword):
	keys = dict()
	keys['ConsumerKey'] = 'dPVleyBRcgwvg8avQuCb0Emyo'
	keys['ConsumerSecret'] = '9u2DgDBW3vMBww2lMvEuqPN1JrTkwoVbY6pCgeR1FwU9hLmXbE'
	keys['AccessToken'] = '915677970-L73XsdyABhajS0O7jya2OT2hhcJxps4lBJN27m8C'
	keys['AccessTokenSecret'] = 'pDPXHRmSOJ9HwCUaadCpzALiBTsEOaFXWF4crbsjK0ial'
	acctDict = keys #get_api_keys()

	twitter = Twython(acctDict['ConsumerKey'], acctDict['ConsumerSecret'], acctDict['AccessToken'], acctDict['AccessTokenSecret'])

	response = twitter.search(q=keyword, result_type='recent')
	itemsList = list()
	for tweet in response['statuses']:
		hashtgs = list()
		price = re.search(r'\$\S*', tweet['text'])
		if price is None:
			price ='OFFER'
		else:
			price = price.group(0)
			tweet['text'] = tweet['text'].replace(price, '') #remove price
		for hashtag in tweet['entities']['hashtags']:
			hashtgs.append(hashtag['text'])
			tweet['text'] = tweet['text'].replace('#'+hashtag['text'], '') #remove hashtags
		temp = {'user_handle': tweet['user']['screen_name'], 'user_photo': tweet['user']['profile_image_url'], 'url':'https://twitter.com/statuses/'+ tweet['id_str'], \
		'content': tweet['text'].encode('utf-8'), 'price': price, 'hashtags': hashtgs, 'time': tweet['created_at'] }
		itemsList.append(temp)
		#print tweet['user']['screen_name'], tweet['user']['profile_image_url'], tweet['text'].encode('utf-8'), 'https://twitter.com/statuses/'+ tweet['id_str']	
	return itemsList
开发者ID:gya12,项目名称:Swapp,代码行数:28,代码来源:views.py


示例13: RT

def RT(ID, name):
    """Function that actually retweets tweet"""
    """Takes a ID and username parameter"""
    """Once tweeted log is updated in overall and to date tweetlog"""
    
    config = config_create()
    print("RT")
    #Tid = int(float(ID))
    Tweetusername = config.get('Auth', 'botname')
    #TweetText = 'https://twitter.com/'+Tweetusername+'/status/'+ID
    #ReTweet = 'Hi I am ComicTweetBot!('+tim+') I Retweet Comics! Use #comicretweetbot '+TweetText
    x2 = config.get('Latest_Log', 'currenttweetlog')
    x3 = config.get('Latest_Log', 'overalllog')
    CONSUMER_KEY =  config.get('Auth', 'CONSUMER_KEY') 
    CONSUMER_SECRET = config.get('Auth', 'CONSUMER_SECRET')
    ACCESS_KEY = config.get('Auth', 'ACCESS_KEY')
    ACCESS_SECRET = config.get('Auth', 'ACCESS_SECRET')
    api = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
    tMax = int(float(config.get('Tweet_Delay', 'Max')))
    tMin = int(float(config.get('Tweet_Delay', 'Min')))
    tStep = int(float(config.get('Tweet_Delay', 'Step')))
    Log = open(x2, 'w')
    enterlog = ID+' '+name+ '\n'
    Log.write(enterlog)
    Log2 = open(x3, 'w')
    Log2.write(ID+'\n')
    #api.update_status(status= ReTweet)
    api.retweet(id = ID)
    api.create_favorite(id=ID, include_entities = True)
    #randomize the time for sleep 1.5mins to 5 mins
    rant = random.randrange(tMin, tMax, tStep)
    time.sleep(rant)
开发者ID:MichaelJRanglin,项目名称:Python_TwitterComicBot,代码行数:32,代码来源:comicbot.py


示例14: ajax_user_timeline

def ajax_user_timeline(request):
    if not request.user.is_authenticated() or 'twitter_tokens' not in request.session:
        return HttpResponse("")

    results = {'success': 'False'}
    if request.method != u'GET':
        return HttpResponseBadRequest('Must be GET request')
    if not request.GET.has_key(u'screenname'):
        return HttpResponseBadRequest('screenname missing')
    if not request.GET.has_key(u'max_id'):
        return HttpResponseBadRequest('start id missing')
    if not request.GET.has_key(u'page'):
        return HttpResponseBadRequest('page number missing')
    screenname = request.GET[u'screenname']
    max_id = request.GET[u'max_id']
    page = request.GET[u'page']

    if 'twitter_tokens' in request.session:
        twitter_tokens = request.session['twitter_tokens']
        api = get_authorized_twython(twitter_tokens)
    else: # Get public api if no authentication possible
        api = Twython()

    results['statuses'] = api.getUserTimeline(screen_name=screenname, max_id=max_id, page=page)
    t = get_template('twitter/status_list.html')
    results['success'] = 'True'
    html = t.render(RequestContext(request, results))
    return HttpResponse(html)
开发者ID:yesimon,项目名称:classiwhale,代码行数:28,代码来源:views.py


示例15: __init__

	def __init__(self,text='',image=False,file_photo='/var/www/foto.jpg'):
		CONSUMER_KEY = 'TPcId3ZdR7jCYwec1A'
		CONSUMER_SECRET = '5eY3k8mEpHI0wCD2LSFK4y2b4zlMunbfc9zpEjdNU'
		ACCESS_KEY = '2273997643-dqvuxb4B2oOm2bFE0TKKMjXzt7vfCF7DZgy1HcW'
		ACCESS_SECRET = 'W9LcdB5qRh2dvWjbzR0C366nYQRPZq8f5RTOdvCZKuxFq'

		if(rpi_device):
			api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
			
			if(text==''):
				date = datetime.datetime.now()
				text = date.strftime('%d %b %Y  %I:%M')

			if(image):	
				photo = open(file_photo,'rb')
				try:
					api.update_status_with_media(media=photo, status=text)
				except TwythonError as e:
					logging.error(e)

			else : 
				try:
					api.update_status_with_media(status=text)
				except TwythonError as e:
					logging.error(e)					
				
			logging.info('Tweet sent')
		else : logging.error('Twython lib not found')
开发者ID:mjalvar,项目名称:framework,代码行数:28,代码来源:Tweet.py


示例16: task

def task():
    APP_KEY = "lF79UQiDsP4kUSRlsg1cW3N9g"
    APP_SECRET = "0nIBU4KJcCXCfZKcWKkQZ8bUPcRpl2gc6kAkmDvc5Rq5998X3K"
    ACCESS_TOKEN = "737898701939716100-JaDquL9VV8O7i8OnVjQd6KSYrq98AtR"
    ACCESS_TOKEN_SECRET = "dgvNfhklbUac2MmWQwT3LHKPk04EJWUzJLSkEMQaZM2Aa"

    darkVarderLink = "https://www.youtube.com/watch?v=-bzWSJG93P8"
    eyeOfTigerLink = "https://www.youtube.com/watch?v=btPJPFnesV4"

    energyKey = []
    zneKey = []
    addressKey = []
    differenceVal = []

    twitter = Twython(APP_KEY, APP_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

    #Get Winner and update according Flag
    jsonData = '[{"energy_sum_week":0,"zne_sum_week":90,"address":"215"},{"energy_sum_week":0,"zne_sum_week":90,"address":"1590"},{"energy_sum_week":10,"zne_sum_week":90,"address":"1605"},{"energy_sum_week":130,"zne_sum_week":90,"address":"1715"}]'
    jdata = json.loads(jsonData)
    for d in jdata:
        for key, value in d.iteritems():
            if(key == "energy_sum_week"):
                energyKey.append(value)
            elif(key == "zne_sum_week"):
                zneKey.append(value)
            else:
                addressKey.append(value)

    for x in range(len(energyKey)):
        differenceVal.append(zneKey[x] - energyKey[x])

    winnerIndex = differenceVal.index(max(differenceVal))
    winnerAddress = addressKey[winnerIndex];
    twitter.update_status(status='The winner is ' + winnerAddress +' Street\n' + eyeOfTigerLink)
开发者ID:stcalica,项目名称:WVDashboard,代码行数:34,代码来源:sendTwitter.py


示例17: update_twitter_data

    def update_twitter_data(self):
        twitter = Twython(
            TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET,
            TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET
        )

        # get the data from Twitter API
        twitter_data = twitter.lookup_status(id=','.join(self.tweet_ids()))

        # so ugly
        for tweet_data in twitter_data:
            tweet_data_id = str(tweet_data['id'])
            tweet_data_media = tweet_data.get('entities').get('media')
            tweet_data_photo = tweet_data_media[0].get('media_url_https') if len(tweet_data_media) else None
            tweet_data_text = tweet_data.get('text')
            tweet_data_text = strip_tweet_text(tweet_data_text)
            
            if self.tweet1.endswith(tweet_data_id):
                if not self.tweet1_photo: self.tweet1_photo = tweet_data_photo
                if not self.tweet1_text: self.tweet1_text = tweet_data_text
            if self.tweet2.endswith(tweet_data_id):
                if not self.tweet2_photo: self.tweet2_photo = tweet_data_photo
                if not self.tweet2_text: self.tweet2_text = tweet_data_text
            if self.tweet3.endswith(tweet_data_id):
                if not self.tweet3_photo: self.tweet3_photo = tweet_data_photo
                if not self.tweet3_text: self.tweet3_text = tweet_data_text
            if self.tweet4.endswith(tweet_data_id):
                if not self.tweet4_photo: self.tweet4_photo = tweet_data_photo
                if not self.tweet4_text: self.tweet4_text = tweet_data_text
            if self.tweet5.endswith(tweet_data_id):
                if not self.tweet5_photo: self.tweet5_photo = tweet_data_photo
                if not self.tweet5_text: self.tweet5_text = tweet_data_text
开发者ID:ryanpitts,项目名称:5tories,代码行数:32,代码来源:models.py


示例18: twitteradd

def twitteradd(request, usertoadd):
    #usertoadd = User.get(username=uidtofollow)
    twitterauth = UserSocialAuth.objects.get(user=request.user, provider="twitter")
    if twitterauth is None:
        return False
    oauth_consumer_key = settings.SOCIAL_AUTH_TWITTER_KEY
    oauth_token = twitterauth.extra_data['access_token']['oauth_token']
    #oauth_nonce = "91227c2566963d6ae01eb72f974e964a"
    oauth_nonce = "".join([random.choice(string.letters) for i in xrange(32)])
    oauth_signature = "eGxVJXIYoG%2B9ay0A4E7QxnBHHrI%3D"
    #currenttime = "1381017251"
    currenttime = str(int(time.time()))
    #user_to_follow = "15378324"

    from twython import Twython
    twitter = Twython(settings.SOCIAL_AUTH_TWITTER_KEY,
                      settings.SOCIAL_AUTH_TWITTER_SECRET,
                      twitterauth.extra_data['access_token']['oauth_token'],
                      twitterauth.extra_data['access_token']['oauth_token_secret'])

    try:
        useridtofollow = UserSocialAuth.objects.get(user=usertoadd, provider="twitter").extra_data['id']
    except:
        return False

    try:
        twitter.create_friendship(user_id=useridtofollow)
    except:
        return False

    return True
开发者ID:theopak,项目名称:glassface,代码行数:31,代码来源:views.py


示例19: __oauth

def __oauth(Rate_id):
    """ twitter로부터 인증토큰을 받기 위한 함수 """
    
    try:
        twitter = Twython(current_app.config['TWIT_APP_KEY'], 
                          current_app.config['TWIT_APP_SECRET'])
        callback_svr = current_app.config['TWIT_CALLBACK_SERVER']
        
        auth    = twitter.get_authentication_tokens(
                          callback_url= callback_svr + \
                          url_for('.callback', Rate_id=Rate_id))

        # 중간단계로 받은 임시 인증토큰은 최종인증을 위해 필요하므로 세션에 저장한다. 
        session['OAUTH_TOKEN'] = auth['oauth_token']
        session['OAUTH_TOKEN_SECRET'] = auth['oauth_token_secret']

    except TwythonError as e:
        Log.error("__oauth(): TwythonError , "+ str(e))
        session['TWITTER_RESULT'] = str(e)

        return redirect(url_for('.show_all'))
    

    # 트위터의 사용자 권한 인증 URL로 페이지를 리다이렉트한다.
    return redirect(auth['auth_url'])
开发者ID:kimdongup,项目名称:ratinglog,代码行数:25,代码来源:twitter.py


示例20: fetch_twitter_followers

 def fetch_twitter_followers(self):
     twitter = Twython(APP_KEY_TWITTER, APP_SECRET_TWITTER,
                       OAUTH_TOKEN_TWITTER, OAUTH_TOKEN_SECRET_TWITTER)
     twitter_obj = twitter.get_followers_ids()
     twitter_followers = len(twitter_obj['ids'])
     twitter_followers = '{:,}'.format(int(twitter_followers))
     self.twitter = twitter_followers
开发者ID:xuan6,项目名称:dg,代码行数:7,代码来源:website_footer_social.py



注:本文中的twython.Twython类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python MIscFunctions1.AppendMessageList类代码示例发布时间:2022-05-27
下一篇:
Python botapi.TelegramBot类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap