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

Python tweepy.API类代码示例

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

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



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

示例1: tweet

def tweet(title, url, location=None, parsed_location=None):
    auth = OAuthHandler(app.config['TWITTER_CONSUMER_KEY'], app.config['TWITTER_CONSUMER_SECRET'])
    auth.set_access_token(app.config['TWITTER_ACCESS_KEY'], app.config['TWITTER_ACCESS_SECRET'])
    api = API(auth)
    urllength = 23  # Current Twitter standard for HTTPS (as of Oct 2014)
    maxlength = 140 - urllength - 1 # == 116
    locationtag = u''
    if parsed_location:
        locationtags = []
        for token in parsed_location.get('tokens', []):
            if 'geoname' in token and 'token' in token:
                locname = token['token'].strip()
                if locname:
                    locationtags.append(u'#' + locname.title().replace(u' ', ''))
        locationtag = u' '.join(locationtags)
        if locationtag:
            maxlength -= len(locationtag) + 1
    if not locationtag and location:
        # Make a hashtag from the first word in the location. This catches
        # locations like 'Anywhere' which have no geonameid but are still valid
        locationtag = u'#' + re.split('\W+', location)[0]
        maxlength -= len(locationtag) + 1

    if len(title) > maxlength:
        text = title[:maxlength-1] + u'…'
    else:
        text = title[:maxlength]
    text = text + ' ' + url  # Don't shorten URLs, now that there's t.co
    if locationtag:
        text = text + ' ' + locationtag
    api.update_status(text)
开发者ID:rudimk,项目名称:hasjob,代码行数:31,代码来源:twitter.py


示例2: authenticate

    def authenticate(self, access_token_key='', access_token_secret='', consumer_key='', consumer_secret=''):
        handler = OAuthHandler(consumer_key, consumer_secret)
        handler.set_access_token(access_token_key, access_token_secret)

        api = API(handler)
        twitter_user = api.verify_credentials()

        try:
            twitter_id = twitter_user.id
        except AttributeError:
            user = None
        else:
            try:
                user = User.objects.get(username=twitter_id)
            except User.DoesNotExist:
                user = User.objects.create_user(twitter_id)

            profile = user.get_profile()

            profile.access_token_key = handler.access_token.key
            profile.access_token_secret = handler.access_token.secret

            profile.save()

        return user
开发者ID:beaumartinez,项目名称:rdf,代码行数:25,代码来源:auth.py


示例3: testbasicauth

    def testbasicauth(self):
        auth = BasicAuthHandler(username, password)

        # test accessing twitter API
        api = API(auth)
        s = api.update_status('test %i' % random.randint(1, 1000))
        api.destroy_status(s.id)
开发者ID:Mezgrman,项目名称:tweepy,代码行数:7,代码来源:tests.py


示例4: get_tweets

def get_tweets(count=5):

    try:
        consumer_key = environ['TWITTER_CONSUMER_KEY']
        access_token = environ['TWITTER_ACCESS_TOKEN']
        consumer_secret = environ['TWITTER_CONSUMER_SECRET']
        access_secret = environ['TWITTER_ACCESS_SECRET']
    except KeyError:
        error("No Twitter credentials were found.")
        # We don't have login stuff, bail.
        return []

    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_secret)
    api = API(auth_handler=auth)

    try:
        statuses = api.user_timeline('pythonglasgow', count=count)
    except TweepError:
        error("Failed to read timelime.")
        return []

    tweets = [(status, twitterfy(status.text)) for status in statuses]

    return tweets
开发者ID:charliequinn,项目名称:pythonglasgow,代码行数:25,代码来源:twitter.py


示例5: unwrapped_callback

    def unwrapped_callback(self, resp):
        if resp is None:
            raise LoginCallbackError(_("You denied the request to login"))

        # Try to read more from the user's Twitter profile
        auth = TwitterOAuthHandler(self.consumer_key, self.consumer_secret)
        if self.access_key is not None and self.access_secret is not None:
            auth.set_access_token(self.access_key, self.access_secret)
        else:
            auth.set_access_token(resp['oauth_token'], resp['oauth_token_secret'])
        api = TwitterAPI(auth)
        try:
            twinfo = api.lookup_users(user_ids=[resp['user_id']])[0]
            fullname = twinfo.name
            avatar_url = twinfo.profile_image_url_https.replace('_normal.', '_bigger.')
        except TweepError:
            fullname = None
            avatar_url = None

        return {'userid': resp['user_id'],
                'username': resp['screen_name'],
                'fullname': fullname,
                'avatar_url': avatar_url,
                'oauth_token': resp['oauth_token'],
                'oauth_token_secret': resp['oauth_token_secret'],
                'oauth_token_type': None,  # Twitter doesn't have token types
                }
开发者ID:gonrin,项目名称:lastuser,代码行数:27,代码来源:twitter.py


示例6: TwitterPlayer

class TwitterPlayer(player.Player):
    def __init__(self, model, code, access_token, access_token_secret, opponent):
        player.Player.__init__(self, model, code)
        self._opponent = opponent
        self._last_id = None

        self._auth = OAuthHandler(auth.consumer_key, auth.consumer_secret)
        self._auth.set_access_token(access_token, access_token_secret)
        self._api = API(self._auth)
        self._listener = TwitterListener(self, self._api)
        self._stream = Stream(self._auth, self._listener)

    @property
    def username(self):
        return self._auth.get_username()

    def allow(self):
        print 'This is the opponent\'s turn...'
        self._stream.userstream()

    def update(self, event):
        if event.player == self.code:
            return
        message = '@%s %s' % (self._opponent, self._model.events[-1][1])
        self.tweet(message)

    def tweet(self, message):
        if self._last_id is None:
            self._api.update_status(message)
        else:
            self._api.update_status(message, self._last_id)
开发者ID:benijake,项目名称:twishogi,代码行数:31,代码来源:player.py


示例7: unwrapped_callback

    def unwrapped_callback(self, resp):
        if resp is None:
            raise LoginCallbackError(_("You denied the request to login"))

        # Try to read more from the user's Twitter profile
        auth = TwitterOAuthHandler(self.consumer_key, self.consumer_secret)
        auth.set_access_token(resp['oauth_token'], resp['oauth_token_secret'])
        api = TwitterAPI(auth)
        try:
            twinfo = api.verify_credentials(include_entities='false', skip_status='true', include_email='true')
            fullname = twinfo.name
            avatar_url = twinfo.profile_image_url_https.replace('_normal.', '_bigger.')
            email = getattr(twinfo, 'email', None)
        except TweepError:
            fullname = None
            avatar_url = None
            email = None

        return {'email': email,
                'userid': resp['user_id'],
                'username': resp['screen_name'],
                'fullname': fullname,
                'avatar_url': avatar_url,
                'oauth_token': resp['oauth_token'],
                'oauth_token_secret': resp['oauth_token_secret'],
                'oauth_token_type': None,  # Twitter doesn't have token types
                }
开发者ID:hasgeek,项目名称:lastuser,代码行数:27,代码来源:twitter.py


示例8: tweet

def tweet(title, url, location=None, parsed_location=None, username=None):
    auth = OAuthHandler(app.config["TWITTER_CONSUMER_KEY"], app.config["TWITTER_CONSUMER_SECRET"])
    auth.set_access_token(app.config["TWITTER_ACCESS_KEY"], app.config["TWITTER_ACCESS_SECRET"])
    api = API(auth)
    urllength = 23  # Current Twitter standard for HTTPS (as of Oct 2014)
    maxlength = 140 - urllength - 1  # == 116
    if username:
        maxlength -= len(username) + 2
    locationtag = u""
    if parsed_location:
        locationtags = []
        for token in parsed_location.get("tokens", []):
            if "geoname" in token and "token" in token:
                locname = token["token"].strip()
                if locname:
                    locationtags.append(u"#" + locname.title().replace(u" ", ""))
        locationtag = u" ".join(locationtags)
        if locationtag:
            maxlength -= len(locationtag) + 1
    if not locationtag and location:
        # Make a hashtag from the first word in the location. This catches
        # locations like 'Anywhere' which have no geonameid but are still valid
        locationtag = u"#" + re.split("\W+", location)[0]
        maxlength -= len(locationtag) + 1

    if len(title) > maxlength:
        text = title[: maxlength - 1] + u"…"
    else:
        text = title[:maxlength]
    text = text + " " + url  # Don't shorten URLs, now that there's t.co
    if locationtag:
        text = text + " " + locationtag
    if username:
        text = text + " @" + username
    api.update_status(text)
开发者ID:superstarrajini,项目名称:hasjob,代码行数:35,代码来源:twitter.py


示例9: get

    def get(self, request, *args, **kwargs):
        """
        The GET method controller for the API endpoint and saves the results
        to a CSV file.
        Accepts query strings:
            - keyword: the keyword that searched for
            - count: number of results retrieved (default = 100)
        """
        keyword = request.GET.get('keyword')
        count = request.GET.get('count', 100)
        if not keyword:
            return Response(HTTP_400_BAD_REQUEST)

        auth = twitter_auth()
        api = API(auth, parser=JSONParser())
        data = []
        results = api.search(q=keyword, count=count)
        filename = 'search_{}_{}.csv'.format(
            keyword, datetime.now().isoformat()
        )
        for result in results['statuses']:
            data.append({
                'user': parse_tweet(result['user']['name']),
                'tweet': parse_tweet(result['text'])
            })
        save_to_csv(filename, data)
        response_text = 'Saved {} objects.'.format(
            results['search_metadata']['count']
        )
        return Response(response_text)
开发者ID:vkaracic,项目名称:JARVIS-py,代码行数:30,代码来源:views.py


示例10: unwrapped_callback

    def unwrapped_callback(self, resp):
        if resp is None:
            raise LoginCallbackError(_("You denied the request to login"))

        # Try to read more from the user's Twitter profile
        auth = TwitterOAuthHandler(self.consumer_key, self.consumer_secret)
        if self.access_key is not None and self.access_secret is not None:
            auth.set_access_token(self.access_key, self.access_secret)
        else:
            auth.set_access_token(resp["oauth_token"], resp["oauth_token_secret"])
        api = TwitterAPI(auth)
        try:
            twinfo = api.lookup_users(user_ids=[resp["user_id"]])[0]
            fullname = twinfo.name
            avatar_url = twinfo.profile_image_url_https.replace("_normal.", "_bigger.")
        except TweepError:
            fullname = None
            avatar_url = None

        return {
            "userid": resp["user_id"],
            "username": resp["screen_name"],
            "fullname": fullname,
            "avatar_url": avatar_url,
            "oauth_token": resp["oauth_token"],
            "oauth_token_secret": resp["oauth_token_secret"],
            "oauth_token_type": None,  # Twitter doesn't have token types
        }
开发者ID:divyenduz,项目名称:lastuser,代码行数:28,代码来源:twitter.py


示例11: __init__

    def __init__(self, term='', oauthfile=''):
        threading.Thread.__init__(self)
        self.searchterm = term
        self.name = term
        self.consume = True
        
        listener = MongoDBListener()
        
        try:
            oauth = json.loads(open(oauthfile, 'r').read())
            
            if 'consumer_key' in oauth:
                auth = OAuthHandler(oauth['consumer_key'], oauth['consumer_secret'])
                auth.set_access_token(oauth['access_token'], oauth['access_token_secret'])
                api = API(auth)

                if not api.verify_credentials():
                    raise Exception("Invalid credentials")
            else:
                auth = BasicAuthHandler(oauth['username'], oauth['password'])

        except:
            print "Error logging to Twitter"
            raise
    
        self.stream = Stream(auth, listener, timeout=60)  
开发者ID:EugeneLiang,项目名称:twitterstream-to-mongodb,代码行数:26,代码来源:twitterstreamtomongodb.py


示例12: FaveRetweeter

class FaveRetweeter(object):

    def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):
        self.consumer_key = consumer_key
        self.consumer_secret = consumer_secret

        self.access_token = access_token
        self.access_token_secret = access_token_secret

        self._authorize()

    def _authorize(self):
        oauth_handler = OAuthHandler(self.consumer_key, self.consumer_secret)
        oauth_handler.set_access_token(self.access_token, self.access_token_secret)

        self.tweepy = API(oauth_handler)

    def retweet_fave(self):
        me = self.tweepy.me()

        favorite_count = me.favourites_count
        page = randrange(favorite_count)

        favorites = self.tweepy.favorites(count=1, page=page)
        favorite = favorites[0]

        _retweet(favorite, me)
开发者ID:beaumartinez,项目名称:rdf-cli,代码行数:27,代码来源:api.py


示例13: get_tweets

def get_tweets(tweeter_id, from_id = None):
    #Setup
    #l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = API(auth)

    #Get tweets (status) from Twitter A
    if from_id == None:
        status = api.user_timeline(user_id = tweeter_id, count=amont_of_tweets)
    else:
        status = api.user_timeline(user_id = tweeter_id, count=amont_of_tweets, max_id = from_id)
        status.pop(0) #Remove duplicate first tweet, max_id not included.

    tweetlist = []
    last_id = 0

    #print("Cleaning tweets from :", status.user.screen_name, "id: ", tweeter_id)
    for items in status:
        tweet = {}
        tweet["id"] = items.id
        tweet["user_id"] = tweeter_id
        tweet["nickname"] = items.user.screen_name
        tweet["realname"] = items.user.name
        tweet["date"] = datetime.strptime(str(items.created_at), "%Y-%m-%d %H:%M:%S")
        tweet["text"] = items.text

        tweetlist.append(tweet)
        last_id = items.id

    print("Last ID: ", last_id, "\n")
    return tweetlist, last_id
开发者ID:chrismessiah,项目名称:bachelor-thesis,代码行数:32,代码来源:twitter_mining.py


示例14: FeedTwitter

def FeedTwitter():
    auth = OAuthHandler(CONSUMER_KEY_TWITTER, CONSUMER_SECRET_TWITTER)
    auth.set_access_token(ACCESS_TOKEN_TWITTER, ACCESS_TOKEN_SECRET_TWITTER)
    api = API(auth)
    feed = api.user_timeline(screen_name=CONST_USER_TWITTER, count=COUNT_NUMBER_POST, page=1, include_rts=True)
    tweets = []
    for t in feed:
        if t.in_reply_to_status_id == None:
            try:
                tweet = {"text": t.text, "text_encoded": t.text, "type": "tweet", "created_time": t.created_at,
                         "link":"https://twitter.com/"+CONST_USER_LINK_TWITTER+"/status/" + str(t.id),
                         "link_encoded":urllib.quote_plus("https://twitter.com/"+CONST_USER_LINK_TWITTER+"/status/" + str(t.id)),
                         "user": {"name": t.user.name, "screen_name": "@" + t.user.screen_name,"profile_image":t.user.profile_image_url}}
                if "media" in t.entities:
                    if t.entities['media'][0]['type'] == 'photo':
                        tweet["image"] = t.entities['media'][0]['media_url']
                    else:
                        pass
                        #print t.entities['media'][0]['type']
                else:
                    pass
                    #tweet["image"] = get_randon_image()
                tweets.append(tweet)
            except Exception, e:
                #print(str(e))
                pass
开发者ID:coolirisPunk,项目名称:f12016,代码行数:26,代码来源:views.py


示例15: StreamConsumerThreadClass

class StreamConsumerThreadClass(threading.Thread):
    def __init__(self, term="", oauthfile="", follow=False, user=False, track=False):
        threading.Thread.__init__(self)
        self.searchterm = term
        self.name = term
        self.consume = True
        self.follow = follow
        self.user = user
        self.track = track
        listener = MongoDBListener()

        try:
            oauth = json.loads(open(oauthfile, "r").read())

            if "consumer_key" in oauth:
                auth = OAuthHandler(oauth["consumer_key"], oauth["consumer_secret"])
                auth.set_access_token(oauth["access_token"], oauth["access_token_secret"])
                self.api = API(auth)

                if not self.api.verify_credentials():
                    raise Exception("Invalid credentials")

                self.stream = Stream(auth, listener, timeout=60)

        except:
            print "Error logging to Twitter"
            raise

    def stop_consume(self):
        self.stream.disconnect()

    def run(self):
        now = datetime.datetime.now()
        if self.user:
            print "Twitter Stream of the OAuth user: started at: %s" % (now)
        else:
            print "Twitter Stream with terms: %s started at: %s" % (self.getName(), now)

        connected = False
        while True:
            try:
                if not connected:
                    connected = True
                    if self.user:
                        self.stream.userstream(_with="followings")
                    elif self.follow:
                        user_ids = []
                        for user in self.api.lookup_users([], self.searchterm.split(","), False):
                            user_ids.append(user.id)
                        self.stream.filter(follow=[",".join("{0}".format(n) for n in user_ids)])
                    elif self.track:
                        self.stream.filter(track=[self.searchterm])

            except SSLError, sse:
                print sse
                connected = False
            except Exception, e:
                print "Stream error"
                raise e
开发者ID:openp2pdesign,项目名称:twitterstream-to-mongodb,代码行数:59,代码来源:twitterstreamtomongodb.py


示例16: Twitter

class Twitter():
  def __init__(self, config = None):
    auth = OAuthHandler(unicode(config.consumerKey), unicode(config.consumerSecret))
    auth.set_access_token(unicode(config.accessToken), unicode(config.accessTokenSecret))
    self._api = API(auth)

  def tweet(self, message):
    self._api.update_status(message.encode('utf-8'))
开发者ID:vrachieru,项目名称:f64-consignatie,代码行数:8,代码来源:twitter.py


示例17: get_location_trends

def get_location_trends(locations, auth):

	api = API(auth)

	trends = api.trends_place(locations)
	data = trends[0]
	trends_data = data['trends']
	names = [trend['name'] for trend in trends_data]

	print names
开发者ID:kownet,项目名称:osint-series,代码行数:10,代码来源:location_trends.py


示例18: send_reply

def send_reply(tweetID,screen_name):
	try:
		auth = OAuthHandler(consumer_key, consumer_secret)
		auth.set_access_token(access_token, access_token_secret)
		api = API(auth)
		### at this point I've grabbed the tweet and loaded it to JSON...
		status_message = "@%s You are not supposed to use such words. @stophatebot " % (screen_name)
		api.update_status(status_message, tweetID)
	except Exception, e:
		print e
开发者ID:konarkmodi,项目名称:hack4changestream,代码行数:10,代码来源:send_replies.py


示例19: main

def main():
   	try:
		auth = OAuthHandler(consumer_key, consumer_secret)
		auth.secure = True
		auth.set_access_token(access_token, access_token_secret)
		api = API(auth)
		print(api.me().name)
		stream = Stream(auth, StdOutListener())
		stream.userstream()

    	except BaseException as e:
        	print("Error in main()", e)
开发者ID:zweed4u,项目名称:freeGuacAndChips,代码行数:12,代码来源:chipotleDM.py


示例20: testverifycredentials

    def testverifycredentials(self):
        self.assertNotEqual(self.api.verify_credentials(), False)

        # make sure that `me.status.entities` is not an empty dict
        me = self.api.verify_credentials(include_entities=True)
        self.assertTrue(me.status.entities)

        # `status` shouldn't be included
        me = self.api.verify_credentials(skip_status=True)
        self.assertFalse(hasattr(me, 'status'))

        api = API(BasicAuthHandler('bad', 'password'))
        self.assertEqual(api.verify_credentials(), False)
开发者ID:Mezgrman,项目名称:tweepy,代码行数:13,代码来源:tests.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python tweepy.FileCache类代码示例发布时间:2022-05-27
下一篇:
Python tweelexer.TweeLexer类代码示例发布时间: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