Python twython.TwythonError() Examples

The following are 9 code examples of twython.TwythonError(). 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 twython , or try the search function .
Example #1
Source File: twitterbot.py    From twitterbot with GNU General Public License v2.0 6 votes vote down vote up
def post_tweet(message: str):
    """Post tweet message to account.

    Parameters
    ----------
    message: str
        Message to post on Twitter.
    """
    try:
        twitter = Twython(TwitterAuth.consumer_key,
                          TwitterAuth.consumer_secret,
                          TwitterAuth.access_token,
                          TwitterAuth.access_token_secret)
        twitter.update_status(status=message)
    except TwythonError as e:
        print(e) 
Example #2
Source File: twitterbot.py    From twitterbot with GNU General Public License v2.0 5 votes vote down vote up
def search_and_retweet(query: str, count=10):
    """Search for a query in tweets, and retweet those tweets.

    Parameters
    ----------
    query: str
        A query to search for on Twitter.
    count: int
        Number of tweets to search for. You should probably keep this low
        when you use search_and_retweet() on a schedule (e.g. cronjob).
    """
    try:
        twitter = Twython(TwitterAuth.consumer_key,
                          TwitterAuth.consumer_secret,
                          TwitterAuth.access_token,
                          TwitterAuth.access_token_secret)
        search_results = twitter.search(q=query, count=count)
    except TwythonError as e:
        print(e)
        return
    for tweet in search_results["statuses"]:
        # Make sure we don't retweet any dubplicates.
        if not is_in_logfile(
                    tweet["id_str"], Settings.posted_retweets_output_file):
            try:
                twitter.retweet(id=tweet["id_str"])
                write_to_logfile(
                    tweet["id_str"], Settings.posted_retweets_output_file)
                print("Retweeted {} (id {})".format(shorten_text(
                    tweet["text"], maxlength=40), tweet["id_str"]))
            except TwythonError as e:
                print(e)
        else:
            print("Already retweeted {} (id {})".format(
                shorten_text(tweet["text"], maxlength=40), tweet["id_str"])) 
Example #3
Source File: core.py    From trackthenews with MIT License 5 votes vote down vote up
def tweet(self):
        """Send images to be rendered and tweet them with a text status."""
        square = False if len(self.matching_grafs) == 1 else True
        for graf in self.matching_grafs[:4]:
            self.imgs.append(render_img(graf, square=square))

        twitter = get_twitter_instance()

        media_ids = []

        for img in self.imgs:
            try:
                img_io = BytesIO()
                img.save(img_io, format='jpeg', quality=95)
                img_io.seek(0)
                res = twitter.upload_media(media=img_io)

                media_ids.append(res['media_id'])
            except TwythonError:
                pass

        source = self.outlet + ": " if self.outlet else ''

        # Truncate title to fit in remaining characters.
        # As of 2019-03-03:
        # - Tweets can be 280 characters.
        # - Minus the length of the `source` string.
        # - Minus three more characters for the ellipsis (a two-byte character) and space between the title and the URL.
        # - Links count for 23 characters once they've been wrapped in a t.co URL.
        remaining_chars = 280 - len(source) - 3 - 23
        title = (self.title[:remaining_chars] + '…') if len(self.title) > remaining_chars else self.title

        status = "{}{} {}".format(source, title, self.url)

        twitter.update_status(status=status, media_ids=media_ids)
        print(status)

        self.tweeted = True 
Example #4
Source File: tweet.py    From Python-for-Everyday-Life with MIT License 5 votes vote down vote up
def tweet(twitter, message):
    print('Tweeting: "{}"'.format(message))
    try:
        twitter.update_status(status=message)
        print('Done')
    except TwythonError as e:
        print('Impossible to tweet, reason: {}'.format(e)) 
Example #5
Source File: tweet.py    From Python-for-Everyday-Life with MIT License 5 votes vote down vote up
def search_tweets(twitter, query, how_many=10, kind='recent'):
    try:
        result_set = twitter.search(q=query, count=how_many, result_type=kind)
        return result_set['statuses']
    except TwythonError as e:
        print('Something bad happened, reason: {}'.format(e))
        return [] 
Example #6
Source File: tweet.py    From Python-for-Everyday-Life with MIT License 5 votes vote down vote up
def retweet(twitter, tweet_id):
    print('Retweeting tweet with ID={}'.format(tweet_id))
    try:
        twitter.retweet(id=tweet_id)
        print('Done')
    except TwythonError as e:
        print('Impossible to retweet, reason: {}'.format(e)) 
Example #7
Source File: test_twitter.py    From sneaky-creeper with MIT License 5 votes vote down vote up
def test_send(self):
        try:
            self.channel.send(self.randText)
        except TwythonError as e:
            # something out of our control
            raise SkipTest("Twython error occurred: {}".format(e))

        resp = self.client.get_user_timeline(screen_name=self.testParams['name'])
        if 'text' in resp[0]:
            self.assertEqual(resp[0]['text'], self.randText) 
Example #8
Source File: test_twitter.py    From sneaky-creeper with MIT License 5 votes vote down vote up
def test_receive(self):
        try:
            self.client.update_status(status=self.randText)
        except TwythonError as e:
            # something out of our control
            raise SkipTest("Twython error occurred: {}".format(e))

        tweets = self.channel.receive()
        self.assertEqual(tweets[0], self.randText) 
Example #9
Source File: test_all.py    From sneaky-creeper with MIT License 5 votes vote down vote up
def unit_channel(channel, data):
    """ Test a channel. """

    t = sneakers.Exfil(channel, [])

    # get parameters from config folder
    configPath = os.path.join(basePath, 'config', '{}-config.json'.format(channel))

    try:
        with open(configPath) as f:
            params = json.loads(f.read())
    except:
        raise SkipTest('could not load configuration file for {}'.format(channel))

    t.set_channel_params({'sending': params[channel],
                          'receiving': params[channel]})

    try:
        t.send(data)
    except TwythonError as e:
        # something out of our control
        raise SkipTest("Twython error occurred: {}".format(e))

    got = t.receive()
    if len(data) > 300:
        assert_in(data, got,
          'Failed in assertion for the \'{}\' channel with a very large payload.'.format(channel))
    else:
        assert_in(data, got)

######################################################
#################### Actual Tests ####################
######################################################