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

Python twitter.Twitter类代码示例

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

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



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

示例1: test_user_lookup

 def test_user_lookup(self):
     tw = Twitter(**self.SETTINGS)
     print("Twitter object: ", tw)
     tw.get_access_token()
     user = tw.user_lookup(screen_name='neokluber')
     print("Twitter username: ", user)
     assert user[0]['id_str']
开发者ID:joyanujoy,项目名称:twitter-graph,代码行数:7,代码来源:test_twitter.py


示例2: _run

    def _run(self):
        iterator = None

        # Display what is going to be tracked
        self._animation.queue_tweet(dict(
            user = dict(
                screen_name = 'this_display'
            ),
            text = "tracking \"%s\""%self._track
        ))

        try:
            if self._oauth:
                twitter = Twitter(domain="search.twitter.com", auth = self._oauth)
                i1 = twitter.search(q = self._track)
                i1 = i1['results']
            else:
                i1 = None

            if self._oauth:
                twitter_stream = TwitterStream(auth = self._oauth)
                i2 = twitter_stream.statuses.filter(track = self._track)
            else:
                i2 = None

            iterator = chain(i1, i2)

        except Exception, e:
            print "Could not connect to Twitter, generating random tweets"
            print "\t%s"%e

            iterator = self._random()
开发者ID:nlehuen,项目名称:led_display,代码行数:32,代码来源:tweet.py


示例3: post

    def post(self):
        """Handle the POST method
        """
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        try:
            username = escape(self.request.get('username'))
            password = escape(self.request.get('password'))
            logging.info("Handling request for %s" % username)
            t = Twitter(username, password)
            friends = set([f['screen_name'] for f in t.get_friends()])
            followers = set([f['screen_name'] for f in t.get_followers()])
            to_follow = followers.difference(friends)

            try:
                for user in to_follow:
                    try:
                        t.friendship_create(user, True)
                        logging.info("%s now follows %s" % (username, user))
                    except DownloadError:
                        logging.warning("Download error when %s tried to follow %s" % (username, user))
                        raise

                self.response.out.write(template.render(path, {"success": True}))

            except Exception, e:
                logging.warning("Caught an exception %s when %s tried to follow %s: %s" % (e, username, user))
                raise

        except DeadlineExceededError:
            self.response.out.write(template.render(path, {"error": True}))
开发者ID:ghoseb,项目名称:followtwits,代码行数:30,代码来源:followtwits.py


示例4: render_note_list_as_html

def render_note_list_as_html(notes):
    twitter = Twitter()
    twitter.search('from:rybesh')
    return render_template(
        'notes.html',
        notes=notes,
        tdata=twitter.search('from:rybesh'))
开发者ID:rybesh,项目名称:helpdesk,代码行数:7,代码来源:server.py


示例5: render_helprequest_list_as_html

def render_helprequest_list_as_html(helprequests):
    twitter = Twitter()
    twitter.search('from:rybesh')
    return render_template(
        'helprequests+microdata+rdfa.html',
        helprequests=helprequests,
        tdata=twitter.search('from:rybesh'))
开发者ID:qcxu,项目名称:helpdesk,代码行数:7,代码来源:server.py


示例6: test_twitter

class test_twitter(unittest.TestCase):

    def setUp(self):
        self.t = Twitter()

    def test_get_suburb(self):
        # need tests for oauth failure
        # t.get_tweet()
        # only works when you know what the most recent tweet on twitter is,
        # and it is a suburb with art in it (not Charnwood!)
        # self.assertEqual(self.t.get_suburb(), 'Charnwood', "Tweet not found")
        # self.assertEqual(self.t.get_suburb(), None, "same tweet again")
        None

    def test_parse_tweets(self):
        test = '[{"created_at":"Sat Jul 12 01:22:32 +0000 2014",'
        test = test + '"id":487768939548536840,"id_str":"487768939548536840",'
        test = test + '"text":"@mhvgovhacktest Show me a Parkes sculpture"}]'
        jsontest = json.loads(test)
        self.assertEqual(self.t.parse_tweets(jsontest), 'PARKES', "valid suburb")
        self.assertEqual(self.t.parse_tweets(jsontest), None, "same tweet again")
        test = '[{"created_at":"Sat Jul 12 01:22:32 +0000 2014",'
        test = test + '"id":487768939548536840,"id_str":"487768939548536840",'
        test = test + '"text":"@mhvgovhacktest Show me a Charnwood sculpture"}]'
        jsontest = json.loads(test)
        self.assertEqual(self.t.parse_tweets(jsontest), None, "invalid suburb")

    def tearDown(self):
        del self.t
开发者ID:PrototypeDino,项目名称:govhack2014,代码行数:29,代码来源:test_twitter.py


示例7: __init__

    def __init__(self, token=None):
        self.token = token

        config = md.get_app_config()
        
        if token:
            self.twitter = Twitter(
                oauth_token=self.token.oauth_token,
                oauth_token_secret=self.token.oauth_token_secret,
                    
                consumer_key=config.consumer_key,
                consumer_secret=config.consumer_secret,
                request_token_url=config.request_token_url,
                access_token_url=config.access_token_url,
                authorize_url=config.authorize_url,
                authenticate_url=config.authenticate_url,
                api_url=config.api_url,
                search_api_url=config.search_api_url
            )
        else:
            self.twitter = Twitter(                    
                consumer_key=config.consumer_key,
                consumer_secret=config.consumer_secret,
                request_token_url=config.request_token_url,
                access_token_url=config.access_token_url,
                authorize_url=config.authorize_url,
                authenticate_url=config.authenticate_url,
                api_url=config.api_url,
                search_api_url=config.search_api_url
            )
开发者ID:tongsu,项目名称:twitdao,代码行数:30,代码来源:twitdao.py


示例8: test_post_only_text

 def test_post_only_text(self):
     t = Twitter(**twitter_access)
     tweet_text = "This is a test for plain text tweet at %r" % (_timenow())
     output = t.post_tweet(text=tweet_text)
     return_tweet_text = output.get('text')
     _add_to_test_tweets(output.get('id'), "text_only")
     self.assertEqual(tweet_text, return_tweet_text)
开发者ID:rakshit-agrawal,项目名称:python-twitter-apps,代码行数:7,代码来源:test_twitter.py


示例9: TwitterTests

class TwitterTests(unittest.TestCase):

    def setUp(self):
        self.twitter = Twitter(CUR_DIR + "/test_crossfit.tweets", CUR_DIR + "/test_stop_words.txt")

    def test_data_preprocess(self):
        processor = TwitterDataPreprocessor()

        p_entry1 = processor.preprocess("\"There are no office hours for champions.\"—Paul Dietzel	@CrossFitGames")
        p_entry2 = processor.preprocess("Saturday 6-21-14 - http://t.co/ZtQWUsfal1 http://t.co/jPICqL3adi	@ReebokCrossFit1")
        p_entry3 = processor.preprocess("Crossfit Named - Kristan Clever  Valley CrossFit :	@Cleverhandz")

        text1 = p_entry1[0].strip()
        screen_name1 = p_entry1[1].strip()
        text2 = p_entry2[0].strip()
        screen_name2 = p_entry2[1].strip()
        text3 = p_entry3[0].strip()
        screen_name3 = p_entry3[1].strip()

        self.assertEqual(text1, "there are no office hours for champions paul dietzel")
        self.assertEqual(screen_name1, "crossfitgames")
        self.assertEqual(text2, "saturday 6 21 14 http t co ztqwusfal1 http t co jpicql3adi")
        self.assertEqual(screen_name2, "reebokcrossfit1")
        self.assertEqual(text3, "crossfit named kristan clever valley crossfit")
        self.assertEqual(screen_name3, "cleverhandz")

    def test_twitter_data_building(self):
        self.twitter.load_tweets_and_build_index()
开发者ID:UIKit0,项目名称:simple-search-engine,代码行数:28,代码来源:test_twitter.py


示例10: trainTwitter

def trainTwitter(username):
  global model
  yield ("Training on twitter for @{}".format(username))
  t = Twitter()

  model = NGram(t.getTweets(username), 2)
  yield "Trained"
开发者ID:FloatingGhost,项目名称:SkypeBot,代码行数:7,代码来源:discord_machinelearning.py


示例11: Funlink

class Funlink():
    regexpattern = r':(.+) (?:PRIVMSG) ([\S]+) :.addurl(?: (.+))'
    
    def __init__(self):
        self.Twitter = Twitter("","")
        self.YouTube = YouTube()
        
    def handleInput(self,Matchlist):
        Source = Matchlist[0]
        Target = Matchlist[1]
        Text = Matchlist[2].split()
        
        try:
            URL = tinyurl.create_one(Text[0])
        except Exception:
            PrivMsg(Target,"4Error in 'TINYURL.Modul' >> '" + str(Exception) + "'")
            return
        
        Nick = re.match("(.+?)!", Source).group(1)
        
        if (len(Text) >= 2) or (re.search("(?:.+)youtube.com/(?:.+)v=(\w+)",Text[0]) and len(Text) == 1): #Beschreibung mit angegeben            
            x = "[" + Nick + "] "
            
            #Zusatzinformation ermitteln, wie [YouTube] [PNG] [TIF]
            if (re.search("(?:.+)youtube.com/(?:.+)v=(\w+)",Text[0])):
                x += "[YouTube] "
            elif (re.search("(\w+).rofl.to",Text[0])):
                r = re.search("(\w+).rofl.to",Text[0]).group(1)
                x += "[rofl.to] (" + str(r) +") "
            elif (re.search("collegehumor.com/(\w+)",Text[0])):
                r = re.search("collegehumor.com/(\w+)",Text[0]).group(1)
                x += "[CollegeHumor] (" + str(r) + ")"
            elif (re.search("newgrounds.com/",Text[0])):
                x += "[Newsground] "
            else:
                try:
                    Tag = re.search("\.(bmp|jpg|gif|img|jp2|jpeg|png|psd|tga|tif|txt)$",Text[0]).group(1)
                    x += "[" + Tag.upper() + "] "
                except:
                    pass
            
            if (len(Text) > 1):
                x += URL + " " + " ".join(Text[1:])
            else:
                r = re.search("(?:.+)youtube.com/(?:.+)v=([-_\w]+)",Text[0]).group(1)
                t = self.YouTube.getInfo(r)
                x += URL + " " + t
            
            #Twitter Tweets dürfen nicht länger als 140 Zeichen sein
            if (len(x) <= 140):
                self.Twitter.sendTweet(x)
                PrivMsg(Target,"hinzugefügt! - http://twitter.com/fptlnk","15Funlink:07 ")
            else:
                PrivMsg(Target,"Beschreibung zu lang. Max 140 Zeichen. Dein Add war " \
                + str(len(x)) + " Zeichen lang.","15Funlink:07 ")
        else: #Keine Beschreibung
                PrivMsg(Target,"Die Beschreibung fehlt!","15Funlink:07 ")
开发者ID:msteinhoff,项目名称:foption-bot,代码行数:57,代码来源:funlink.py


示例12: search

def search(keywords):
    """Search the twitter timeline for keywords"""
    twitter_search = Twitter(domain="search.twitter.com")
    
    response = twitter_search.search(q=keywords)
    
    if response:
        return response['results']
    else:
        return None  # pragma: no cover
开发者ID:tetious,项目名称:podiobooks,代码行数:10,代码来源:twitter_utils.py


示例13: test_get_friends

    def test_get_friends(self):
        tw = Twitter(**self.SETTINGS)
        print("Twitter object: ", tw)
        tw.get_access_token()
        user = tw.user_lookup(screen_name='neokluber')
        uid = user[0]['id_str']

        friend_list = tw.get_friends(uid)
        print("Friends list: ", friend_list)
        assert isinstance(friend_list, list)
        assert friend_list
开发者ID:joyanujoy,项目名称:twitter-graph,代码行数:11,代码来源:test_twitter.py


示例14: auth

def auth(request):
    """Kick off the OAuth process"""
    tw = Twitter()
    try:
        token = tw.new_request_token()
    except DownloadError:
        return fail(request, _(u"Twitter is not responding!"
            u" Refresh to try again."))
    auth_url = tw.authorisation_url(token)
    request.session["unauthed_token"] = token.to_string()   
    return HttpResponseRedirect(auth_url)
开发者ID:afternoon,项目名称:followize,代码行数:11,代码来源:views.py


示例15: test_get_settings_geo_true

    def test_get_settings_geo_true(self):
        """
        This test should pass if user has turned the  account setting for Tweet location on using Twitter web/app
        :return:
        :rtype:
        """
        t = Twitter(**twitter_access)
        settings = t.get_account_settings()
        geo = settings.get('geo_enabled')

        self.assertEqual(True, geo)
开发者ID:rakshit-agrawal,项目名称:python-twitter-apps,代码行数:11,代码来源:test_twitter.py


示例16: _scrape_twitter_for_latest

def _scrape_twitter_for_latest():
    """Scrape Twitter for interesting, new Python tips."""
    # This is the secret sauce: search Twitter for '#python tip' tweets that
    # are newer than our current newest.
    new_tweet = Tip.query.newest_tip()
    tweet_id = new_tweet.url.split('/')[-1] if new_tweet else None
    twitter_search = Twitter(domain='search.twitter.com')
    hits = twitter_search.search(q='#python tip', since_id=tweet_id)['results']
    # And now filter out all the retweets.
    not_old_rts = [t for t in hits if not _is_oldstyle_rt(t)]
    embedded_tweets = [_get_embedded(t['id_str']) for t in not_old_rts]
    return [t for t in embedded_tweets if not _is_newstyle_rt(t)]
开发者ID:gthank,项目名称:pytips,代码行数:12,代码来源:manage.py


示例17: test_post_with_media

    def test_post_with_media(self):
        t = Twitter(**twitter_access)
        tweet_text = "This is a test for tweet with 3 media at %r. Pictures from Pixabay." % (_timenow())
        jpegs = ['m01.jpg', 'm02.jpg', 'm03.jpg']
        media_list = [os.path.join('testing', i) for i in jpegs]
        output = t.post_tweet(text=tweet_text, media=media_list)
        return_tweet_text = output.get('text')
        _add_to_test_tweets(output.get('id'), "with_media")

        media_urls = [i['media_url_https'] for i in output['extended_entities']['media']]

        self.assertEqual(len(media_list), len(media_urls))
开发者ID:rakshit-agrawal,项目名称:python-twitter-apps,代码行数:12,代码来源:test_twitter.py


示例18: test_post_with_latlong_geo_true

    def test_post_with_latlong_geo_true(self):
        t = Twitter(**twitter_access)
        ll = (37.000880, -122.062309)
        tweet_text = "This is a test for plain text tweet with location at %r" % (_timenow())
        output = t.post_tweet(text=tweet_text, latlong=ll)
        return_tweet_text = output.get('text')
        _add_to_test_tweets(output.get('id'), "text_geo")

        self.assertEqual(tweet_text, return_tweet_text)
        if t.get_account_settings().get('geo_enabled'):
            return_ll = tuple(output['geo']['coordinates'])
            self.assertAlmostEqual(ll, return_ll)
开发者ID:rakshit-agrawal,项目名称:python-twitter-apps,代码行数:12,代码来源:test_twitter.py


示例19: test_get_limits

    def test_get_limits(self):
        tw = Twitter(**self.SETTINGS)
        print("Twitter object: ", tw)
        tw.get_access_token()

        limits = tw.get_limits()
        print("Limits: ", limits)

        assert (limits.get('resources').get('friends').get('/friends/ids')
                .get('remaining'))

        assert (limits.get('resources').get('users').get('/users/lookup')
                .get('remaining'))
开发者ID:joyanujoy,项目名称:twitter-graph,代码行数:13,代码来源:test_twitter.py


示例20: test_get_timeline

    def test_get_timeline(self):
        t = Twitter(**twitter_access)
        user = twitter_username
        count = 6
        output = t.get_user_timeline(user=user, count=count)
        resp_user = set([i['user']['screen_name'] for i in output])

        # Set the ID for latest tweet before tests
        _write_top_tweet_file(output[0]['id'])

        self.assertEqual(1, len(resp_user))
        self.assertEqual(user, list(resp_user)[0])
        self.assertEqual(count, len(output))
开发者ID:rakshit-agrawal,项目名称:python-twitter-apps,代码行数:13,代码来源:test_twitter.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python app.add_option函数代码示例发布时间:2022-05-27
下一篇:
Python twitter.read_token_file函数代码示例发布时间: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