Python twitter.Api() Examples

The following are 30 code examples of twitter.Api(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twitter , or try the search function .
Example #1
Source File: twitter.py    From mqttwarn with Eclipse Public License 2.0 6 votes vote down vote up
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 
Example #2
Source File: notifiers.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: happyfuntokenizer.py    From python-stanford-corenlp with MIT License 6 votes vote down vote up
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") 
Example #4
Source File: twitteraction.py    From pastepwn with MIT License 6 votes vote down vote up
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 
Example #5
Source File: deletetweets.py    From delete-tweets with ISC License 6 votes vote down vote up
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() 
Example #6
Source File: twitter.py    From quantified-self with MIT License 6 votes vote down vote up
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 
Example #7
Source File: test_tweets.py    From moa with MIT License 6 votes vote down vote up
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,
        ) 
Example #8
Source File: app.py    From moa with MIT License 6 votes vote down vote up
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() 
Example #9
Source File: pull_twitter.py    From pytrader with MIT License 6 votes vote down vote up
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() 
Example #10
Source File: twitter_test.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testGetStatus(self):
    '''Test the twitter.Api GetStatus method'''
    self._AddHandler('http://twitter.com/statuses/show/89512102.json',
                     curry(self._OpenTestData, 'show-89512102.json'))
    status = self._api.GetStatus(89512102)
    self.assertEqual(89512102, status.id)
    self.assertEqual(718443, status.user.id) 
Example #11
Source File: itemshop.py    From Athena with MIT License 5 votes vote down vote up
def Tweet(self, date: str):
        """
        Tweet the current `itemshop.png` local file to Twitter using the credentials provided
        in `configuration.json`.
        """

        try:
            twitterAPI = twitter.Api(
                consumer_key=self.twitterAPIKey,
                consumer_secret=self.twitterAPISecret,
                access_token_key=self.twitterAccessToken,
                access_token_secret=self.twitterAccessSecret,
            )

            twitterAPI.VerifyCredentials()
        except Exception as e:
            log.critical(f"Failed to authenticate with Twitter, {e}")

            return

        body = f"#Fortnite Item Shop for {date}"

        if self.supportACreator is not None:
            body = f"{body}\n\nSupport-a-Creator Code: {self.supportACreator}"

        try:
            with open("itemshop.png", "rb") as shopImage:
                twitterAPI.PostUpdate(body, media=shopImage)

            log.info("Tweeted Item Shop")
        except Exception as e:
            log.critical(f"Failed to Tweet Item Shop, {e}") 
Example #12
Source File: twitter_test.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testDestroyStatus(self):
    '''Test the twitter.Api DestroyStatus method'''
    self._AddHandler('http://twitter.com/statuses/destroy/103208352.json',
                     curry(self._OpenTestData, 'status-destroy.json'))
    status = self._api.DestroyStatus(103208352)
    self.assertEqual(103208352, status.id) 
Example #13
Source File: twitter_test.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testPostUpdate(self):
    '''Test the twitter.Api PostUpdate method'''
    self._AddHandler('http://twitter.com/statuses/update.json',
                     curry(self._OpenTestData, 'update.json'))
    status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей')
    # This is rather arbitrary, but spot checking is better than nothing
    self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text) 
Example #14
Source File: twitter_test.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testGetReplies(self):
    '''Test the twitter.Api GetReplies method'''
    self._AddHandler('http://twitter.com/statuses/replies.json?page=1',
                     curry(self._OpenTestData, 'replies.json'))
    statuses = self._api.GetReplies(page=1)
    self.assertEqual(36657062, statuses[0].id) 
Example #15
Source File: twitter_test.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testGetFriends(self):
    '''Test the twitter.Api GetFriends method'''
    self._AddHandler('http://twitter.com/statuses/friends.json?page=1',
                     curry(self._OpenTestData, 'friends.json'))
    users = self._api.GetFriends(page=1)
    buzz = [u.status for u in users if u.screen_name == 'buzz']
    self.assertEqual(89543882, buzz[0].id) 
Example #16
Source File: twitter_test.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testGetFeatured(self):
    '''Test the twitter.Api GetFeatured method'''
    self._AddHandler('http://twitter.com/statuses/featured.json',
                     curry(self._OpenTestData, 'featured.json'))
    users = self._api.GetFeatured()
    # This is rather arbitrary, but spot checking is better than nothing
    stevenwright = [u.status for u in users if u.screen_name == 'stevenwright']
    self.assertEqual(86991742, stevenwright[0].id) 
Example #17
Source File: twitter_test.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testGetDirectMessages(self):
    '''Test the twitter.Api GetDirectMessages method'''
    self._AddHandler('http://twitter.com/direct_messages.json?page=1',
                     curry(self._OpenTestData, 'direct_messages.json'))
    statuses = self._api.GetDirectMessages(page=1)
    self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', statuses[0].text) 
Example #18
Source File: twitter_test.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testPostDirectMessage(self):
    '''Test the twitter.Api PostDirectMessage method'''
    self._AddHandler('http://twitter.com/direct_messages/new.json',
                     curry(self._OpenTestData, 'direct_messages-new.json'))
    status = self._api.PostDirectMessage('test', u'Моё судно на воздушной подушке полно угрей')
    # This is rather arbitrary, but spot checking is better than nothing
    self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text) 
Example #19
Source File: twitter_test.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testDestroyDirectMessage(self):
    '''Test the twitter.Api DestroyDirectMessage method'''
    self._AddHandler('http://twitter.com/direct_messages/destroy/3496342.json',
                     curry(self._OpenTestData, 'direct_message-destroy.json'))
    status = self._api.DestroyDirectMessage(3496342)
    # This is rather arbitrary, but spot checking is better than nothing
    self.assertEqual(673483, status.sender_id) 
Example #20
Source File: twitter_test.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testCreateFriendship(self):
    '''Test the twitter.Api CreateFriendship method'''
    self._AddHandler('http://twitter.com/friendships/create/dewitt.json',
                     curry(self._OpenTestData, 'friendship-create.json'))
    user = self._api.CreateFriendship('dewitt')
    # This is rather arbitrary, but spot checking is better than nothing
    self.assertEqual(673483, user.id) 
Example #21
Source File: twitter_test.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testGetUser(self):
    '''Test the twitter.Api GetUser method'''
    self._AddHandler('http://twitter.com/users/show/dewitt.json',
                     curry(self._OpenTestData, 'show-dewitt.json'))
    user = self._api.GetUser('dewitt')
    self.assertEqual('dewitt', user.screen_name)
    self.assertEqual(89586072, user.status.id) 
Example #22
Source File: trainers.py    From Fox-V3 with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, storage, **kwargs):
        super(TwitterTrainer, self).__init__(storage, **kwargs)
        from twitter import Api as TwitterApi

        # The word to be used as the first search term when searching for tweets
        self.random_seed_word = kwargs.get('random_seed_word', 'random')
        self.lang = kwargs.get('twitter_lang')

        self.api = TwitterApi(
            consumer_key=kwargs.get('twitter_consumer_key'),
            consumer_secret=kwargs.get('twitter_consumer_secret'),
            access_token_key=kwargs.get('twitter_access_token_key'),
            access_token_secret=kwargs.get('twitter_access_token_secret')
        ) 
Example #23
Source File: __init__.py    From Chaos with MIT License 5 votes vote down vote up
def __init__(self, path):
        self.__twitter_keys = misc.GetKeys(path)
        self.__api = twitter.Api(consumer_key=str(self.__twitter_keys['consumer_key']),
                                 consumer_secret=str(self.__twitter_keys['consumer_secret']),
                                 access_token_key=str(self.__twitter_keys['access_token']),
                                 access_token_secret=str(self.__twitter_keys['access_secret'])) 
Example #24
Source File: photos.py    From twitter-photos with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, user=None, list_slug=None, outdir=None,
                 num=None, parallel=False, increment=False, size=None,
                 exclude_replies=False, tl_type=None, test=False):
        """
        :param user: The screen_name of the user whom to return results for
        :param list_slug: The slug identifying the list owned by the `user`
        :param outdir: The output directory (absolute path)
        :param num: Number of most recent photos to download from each
            related user
        :param parallel: A boolean indicating whether parallel download is
            enabled
        :param increment: A boolean indicating whether to download only new
            photos since last download
        :param: Photo size represented as a string (one of `MEDIA_SIZES`)
        :param: A boolean indicating whether to exlude replies tweets
        :param type: Timeline type represented as a string (one of `TIMELINE_TYPES`)
        :param test: A boolean indicating whether in test mode
        """
        self.user = user
        self.list_slug = list_slug
        self.outdir = outdir
        self.num = num
        self.parallel = parallel
        self.increment = increment
        self.size = size
        self.exclude_replies = exclude_replies
        self.tl_type = tl_type
        self.test = test
        if not self.test:
            self.api = twitter.Api(consumer_key=CONSUMER_KEY,
                                   consumer_secret=CONSUMER_SECRET,
                                   access_token_key=ACCESS_TOKEN,
                                   access_token_secret=ACCESS_TOKEN_SECRET)
        else:
            self.api = TestAPI()
        self.auth_user = None
        self.photos = {}
        self.max_ids = {}
        self.since_ids = {}
        self._downloaded = 0
        self._total = 0 
Example #25
Source File: twitterinterface.py    From ffw with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #26
Source File: twitter_test.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testGetPublicTimeline(self):
    '''Test the twitter.Api GetPublicTimeline method'''
    self._AddHandler('http://twitter.com/statuses/public_timeline.json?since_id=12345',
                     curry(self._OpenTestData, 'public_timeline.json'))
    statuses = self._api.GetPublicTimeline(since_id=12345)
    # This is rather arbitrary, but spot checking is better than nothing
    self.assertEqual(20, len(statuses))
    self.assertEqual(89497702, statuses[0].id) 
Example #27
Source File: malicious_site_notifier.py    From hack4career with Apache License 2.0 5 votes vote down vote up
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 
Example #28
Source File: Fetch_Data_Media_Twitter.py    From StockRecommendSystem with MIT License 5 votes vote down vote up
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 
Example #29
Source File: fpGrowth.py    From AILearners with Apache License 2.0 5 votes vote down vote up
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 
Example #30
Source File: tweet.py    From tau with The Unlicense 5 votes vote down vote up
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