当前位置: 首页>>代码示例>>Python>>正文


Python twitter.Api方法代码示例

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


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

示例1: plugin

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def plugin(srv, item):
    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target)

    twitter_keys = item.addrs

    twapi = twitter.Api(
        consumer_key=twitter_keys[0],
        consumer_secret=twitter_keys[1],
        access_token_key=twitter_keys[2],
        access_token_secret=twitter_keys[3]
    )

    text = item.message[0:138]
    try:
        srv.logging.debug("Sending tweet to %s..." % (item.target))
        res = twapi.PostUpdate(text, trim_user=False)
        srv.logging.debug("Successfully sent tweet")
    except twitter.TwitterError as e:
        srv.logging.error("TwitterError: %s" % e)
        return False
    except Exception as e:
        srv.logging.error("Error sending tweet to %s: %s" % (item.target, e))
        return False

    return True 
开发者ID:jpmens,项目名称:mqttwarn,代码行数:27,代码来源:twitter.py

示例2: tokenize_random_tweet

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def tokenize_random_tweet(self):
        """
        If the twitter library is installed and a twitter connection
        can be established, then tokenize a random tweet.
        """
        try:
            import twitter
        except ImportError:
            print("Apologies. The random tweet functionality requires the Python twitter library: http://code.google.com/p/python-twitter/")
        from random import shuffle
        api = twitter.Api()
        tweets = api.GetPublicTimeline()
        if tweets:
            for tweet in tweets:
                if tweet.user.lang == 'en':
                    return self.tokenize(tweet.text)
        else:
            raise Exception("Apologies. I couldn't get Twitter to give me a public English-language tweet. Perhaps try again") 
开发者ID:stanfordnlp,项目名称:python-stanford-corenlp,代码行数:20,代码来源:happyfuntokenizer.py

示例3: getLotsOfTweets

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def getLotsOfTweets(searchStr):
    CONSUMER_KEY = ''
    CONSUMER_SECRET = ''
    ACCESS_TOKEN_KEY = ''
    ACCESS_TOKEN_SECRET = ''
    api = twitter.Api(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET,
                      access_token_key=ACCESS_TOKEN_KEY, 
                      access_token_secret=ACCESS_TOKEN_SECRET)
    #you can get 1500 results 15 pages * 100 per page
    resultsPages = []
    for i in range(1,15):
        print "fetching page %d" % i
        searchResults = api.GetSearch(searchStr, per_page=100, page=i)
        resultsPages.append(searchResults)
        sleep(6)
    return resultsPages 
开发者ID:aimi-cn,项目名称:AILearners,代码行数:18,代码来源:fpGrowth.py

示例4: __init__

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def __init__(self, slackbot=None):
        self.logger = Logger().get_logger()

        self.data_handler = DataHandler()

        self.api = twitter.Api(
            consumer_key=Config.open_api.twitter.CONSUMER_KEY,
            consumer_secret=Config.open_api.twitter.CONSUMER_SECRET,
            access_token_key=Config.open_api.twitter.ACCESS_TOKEN_KEY,
            access_token_secret=Config.open_api.twitter.ACCESS_TOKEN_SECRET,
        )

        if slackbot is None:
            self.slackbot = SlackerAdapter(
                channel=Config.slack.channel.get("SNS", "#general")
            )
        else:
            self.slackbot = slackbot 
开发者ID:DongjunLee,项目名称:quantified-self,代码行数:20,代码来源:twitter.py

示例5: handle

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def handle(self, *args, **options):

        api = twitter.Api(consumer_key=settings.TWITTER_CONSUMER_KEY,
                          consumer_secret=settings.TWITTER_CONSUMER_SECRET,
                          access_token_key=settings.TWITTER_ACCESS_TOKEN_KEY,
                          access_token_secret=settings.TWITTER_ACCESS_TOKEN_SECRET)

        for currency_symbol in settings.SOCIAL_NETWORK_SENTIMENT_CONFIG['twitter']:
            print(currency_symbol)
            results = api.GetSearch("$" + currency_symbol, count=200)
            for tweet in results:

                if SocialNetworkMention.objects.filter(network_name='twitter', network_id=tweet.id).count() == 0:
                    snm = SocialNetworkMention.objects.create(
                        network_name='twitter',
                        network_id=tweet.id,
                        network_username=tweet.user.screen_name,
                        network_created_on=datetime.datetime.fromtimestamp(tweet.GetCreatedAtInSeconds()),
                        text=tweet.text,
                        symbol=currency_symbol,
                    )
                    snm.set_sentiment()
                    snm.save() 
开发者ID:owocki,项目名称:pytrader,代码行数:25,代码来源:pull_twitter.py

示例6: catch_up_twitter

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def catch_up_twitter(bridge):
    if bridge.twitter_last_id == 0 and bridge.twitter_oauth_token:
        # get twitter ID
        twitter_api = twitter.Api(
                consumer_key=app.config['TWITTER_CONSUMER_KEY'],
                consumer_secret=app.config['TWITTER_CONSUMER_SECRET'],
                access_token_key=bridge.twitter_oauth_token,
                access_token_secret=bridge.twitter_oauth_secret,
                tweet_mode='extended'  # Allow tweets longer than 140 raw characters
        )
        try:
            tl = twitter_api.GetUserTimeline()
        except TwitterError as e:
            flash(f"Twitter error: {e}")
        else:
            if len(tl) > 0:
                bridge.twitter_last_id = tl[0].id
                d = datetime.strptime(tl[0].created_at, '%a %b %d %H:%M:%S %z %Y')
                bridge.md.last_tweet = d
            else:
                bridge.twitter_last_id = 0

            bridge.updated = datetime.now()
            db.session.commit() 
开发者ID:foozmeat,项目名称:moa,代码行数:26,代码来源:app.py

示例7: setUp

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def setUp(self):
        moa_config = os.environ.get('MOA_CONFIG', 'TestingConfig')
        self.c = getattr(importlib.import_module('config'), moa_config)

        self.settings = TSettings()

        FORMAT = '%(asctime)-15s %(message)s'
        logging.basicConfig(format=FORMAT)

        self.l = logging.getLogger()
        self.l.setLevel(logging.INFO)

        self.api = twitter.Api(
                consumer_key=self.c.TWITTER_CONSUMER_KEY,
                consumer_secret=self.c.TWITTER_CONSUMER_SECRET,
                tweet_mode='extended',  # Allow tweets longer than 140 raw characters

                # Get these 2 from the bridge
                access_token_key=self.c.TWITTER_OAUTH_TOKEN,
                access_token_secret=self.c.TWITTER_OAUTH_SECRET,
        ) 
开发者ID:foozmeat,项目名称:moa,代码行数:23,代码来源:test_tweets.py

示例8: delete

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def delete(tweetjs_path, since_date, until_date, filters, s, min_l, min_r, dry_run=False):
    with io.open(tweetjs_path, mode="r", encoding="utf-8") as tweetjs_file:
        count = 0

        api = twitter.Api(consumer_key=os.environ["TWITTER_CONSUMER_KEY"],
                          consumer_secret=os.environ["TWITTER_CONSUMER_SECRET"],
                          access_token_key=os.environ["TWITTER_ACCESS_TOKEN"],
                          access_token_secret=os.environ["TWITTER_ACCESS_TOKEN_SECRET"])
        destroyer = TweetDestroyer(api, dry_run)

        tweets = json.loads(tweetjs_file.read()[25:])
        for row in TweetReader(tweets, since_date, until_date, filters, s, min_l, min_r).read():
            destroyer.destroy(row["tweet"]["id_str"])
            count += 1

        print("Number of deleted tweets: %s\n" % count)

    sys.exit() 
开发者ID:koenrh,项目名称:delete-tweets,代码行数:20,代码来源:deletetweets.py

示例9: __init__

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def __init__(
            self,
            consumer_key=None,
            consumer_secret=None,
            access_token_key=None,
            access_token_secret=None,
            template=None,
    ):
        super().__init__()

        self.logger = logging.getLogger(__name__)

        self.twitter_api = twitter.Api(
            consumer_key=consumer_key,
            consumer_secret=consumer_secret,
            access_token_key=access_token_key,
            access_token_secret=access_token_secret,
        )
        self.template = template 
开发者ID:d-Rickyy-b,项目名称:pastepwn,代码行数:21,代码来源:twitteraction.py

示例10: _send_tweet

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def _send_tweet(self, message=None, attachment=None):
        consumer_key = self.config['consumer_key']
        consumer_secret = self.config['consumer_secret']
        access_token = self.config['access_token']
        access_token_secret = self.config['access_token_secret']

        # logger.info("Tautulli Notifiers :: Sending tweet: " + message)

        api = twitter.Api(consumer_key, consumer_secret, access_token, access_token_secret)

        try:
            api.PostUpdate(message, media=attachment)
            logger.info("Tautulli Notifiers :: {name} notification sent.".format(name=self.NAME))
            return True
        except Exception as e:
            logger.error("Tautulli Notifiers :: {name} notification failed: {e}".format(name=self.NAME, e=e))
            return False 
开发者ID:Tautulli,项目名称:Tautulli,代码行数:19,代码来源:notifiers.py

示例11: load

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def load(self):
        filelocation = os.path.join(self.config['basedir'], "tweet.conf")
        rc = TweetRc(filelocation)
        consumer_key = rc.GetConsumerKey()
        consumer_secret = rc.GetConsumerSecret()
        access_key = rc.GetAccessKey()
        access_secret = rc.GetAccessSecret()
        encoding = None
        if not consumer_key or not consumer_secret or not access_key or not access_secret:
            raise Exception("Could not load twitter config in: " + filelocation)

        self.api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret,
                          access_token_key=access_key, access_token_secret=access_secret,
                          input_encoding=encoding) 
开发者ID:dobin,项目名称:ffw,代码行数:16,代码来源:twitterinterface.py

示例12: tweet

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def tweet(txt):
    if debug:
	print "Tweet:", txt
    api = twitter.Api(consumer_key='key',
                      consumer_secret='key',
                      access_token_key='key',
                      access_token_secret='key')
    if debug:
    	print "Twitter:", twitter
    user_timeline = api.PostUpdate(txt.encode("utf-8"))
    if debug:
    	print "Timeline:", user_timeline 
开发者ID:mertsarica,项目名称:hack4career,代码行数:14,代码来源:malicious_site_notifier.py

示例13: getTwitterApi

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def getTwitterApi(root_path):
    global gloabl_api
    if gloabl_api is None:
        import twitter
        config = configparser.ConfigParser()
        config.read(root_path + "/" + "config.ini")
        api_key = config.get('Twitter', 'KEY')
        api_secret = config.get('Twitter', 'SECRET')
        access_token_key = config.get('Twitter', 'TOKEN_KEY')
        access_token_secret = config.get('Twitter', 'TOKEN_SECRET')
        http = config.get('Proxy', 'HTTP')
        https = config.get('Proxy', 'HTTPS')
        proxies = {'http': http, 'https': https}
        gloabl_api = twitter.Api(api_key, api_secret, access_token_key, access_token_secret, timeout = 15, proxies=proxies)
    return gloabl_api 
开发者ID:doncat99,项目名称:StockRecommendSystem,代码行数:17,代码来源:Fetch_Data_Media_Twitter.py

示例14: send_tweet

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def send_tweet(event, context):
    """Post tweet
    """
    with open("twitter_credentials.json", "r") as f:
        credentials = json.load(f)
    t = tw.Api(**credentials)
    try:
        status = tweet_content()
        t.PostUpdate(status=status)
        return "Tweeted {}".format(status)
    except Exception as e:
        return e.message 
开发者ID:tdhopper,项目名称:tau,代码行数:14,代码来源:tweet.py

示例15: get_api

# 需要导入模块: import twitter [as 别名]
# 或者: from twitter import Api [as 别名]
def get_api(consumer_key, consumer_secret, access_key, access_secret):
    api = twitter.Api(consumer_key=consumer_key,
                      consumer_secret=consumer_secret,
                      access_token_key=access_key,
                      access_token_secret=access_secret,
                      sleep_on_rate_limit=True)
    return api 
开发者ID:Data4Democracy,项目名称:collect-social,代码行数:9,代码来源:utils.py


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