Python twython.Twython() Examples

The following are 30 code examples of twython.Twython(). 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: util.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def add_access_token(creds_file=None):
    """
    For OAuth 2, retrieve an access token for an app and append it to a
    credentials file.
    """
    if creds_file is None:
        path = os.path.dirname(__file__)
        creds_file = os.path.join(path, 'credentials2.txt')
    oauth2 = credsfromfile(creds_file=creds_file)
    app_key = oauth2['app_key']
    app_secret = oauth2['app_secret']

    twitter = Twython(app_key, app_secret, oauth_version=2)
    access_token = twitter.obtain_access_token()
    tok = 'access_token={}\n'.format(access_token)
    with open(creds_file, 'a') as infile:
        print(tok, file=infile) 
Example #3
Source File: twitter.py    From sneaky-creeper with MIT License 6 votes vote down vote up
def receive(self):
        APP_KEY = self.param('receiving', 'key')
        APP_SECRET = self.param('receiving', 'secret')
        OAUTH_TOKEN = self.param('receiving', 'token')
        OAUTH_TOKEN_SECRET = self.param('receiving', 'tsecret')
        SCREEN_NAME = self.param('receiving', 'name')

        twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

        user_timeline = twitter.get_user_timeline(screen_name=SCREEN_NAME, count=200, trim_user=True)
        timeline = user_timeline

        # TODO pagination
        # while len(user_timeline) == 200:
        #     max_id = user_timeline[-1]['id'] + 1
        #     user_timeline = twitter.get_user_timeline(screen_name=SCREEN_NAME, count=200, trim_user=True, max_id=max_id)
        #     timeline.extend(user_timeline)

        tweets = []
        for x in reversed(timeline):
            if 'text' in x:
                tweets.append(x['text'].encode('utf-8'))

        return tweets 
Example #4
Source File: twython_facade.py    From resilient-community-apps with MIT License 6 votes vote down vote up
def __init__(self, api_key, api_secret, log, client_args):
        """

        :param api_key: The API KEY for a Twitter Developer App
        :param api_secret: The API Secret for a Twitter Developer App.

        Both of these values are used to acquire a OAuth2 Access Token,
        :param log:
        """
        self.log = log
        self.twitter_auth = Twython(api_key, api_secret, oauth_version=2, client_args=client_args)
        self.access_token = self.twitter_auth.obtain_access_token()
        self.twitter = Twython(api_key, access_token=self.access_token, client_args=client_args)

        log.debug("Access_Token is {}".format(self.access_token))
        del api_secret, self.twitter_auth

        log.info("Deleted API Secret") 
Example #5
Source File: tweet_it.py    From double_pendulum with MIT License 6 votes vote down vote up
def new_tweet(filename=None, status=None):
    """Posts a new tweet.

    Status are the initial conditions, video is attached.
    To successfully post, a valid API key is needed to be stored in `api_key.txt`.

    Args:
        filename (string): name of the file containing video (without extension)
        status (string): text which will be posted as Twitter status
    """
    if filename is None:
        filename, comment = create_content()
        if status is None:
            status = comment

    with open("api_key.txt") as f:
        api_data = f.readline().split(';')
    twitter = Twython(*api_data)

    video = open('./animations/{}.mp4'.format(filename), 'rb')
    response = twitter.upload_video(media=video, media_type='video/mp4')
    twitter.update_status(status=status, media_ids=[response['media_id']]) 
Example #6
Source File: tl_tweets.py    From evtools with MIT License 6 votes vote down vote up
def tweet_search(log, item, limit=50):
    log.debug("   Searching twitter for %s", item)
    check_twitter_config()
    if len(item) > 500:
        log.error("      Search string too long")
        raise Exception("Search string too long: %d", len(item))
    logging.captureWarnings(True)
    old_level = log.getEffectiveLevel()
    log.setLevel(logging.ERROR)
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    try:
        result = twitter.search(q=item, count=limit)
    except TwythonAuthError as e:
        twitter_auth_issue(e)
        raise
    except:
        raise
    log.setLevel(old_level)
    return result 
Example #7
Source File: tl_tweets.py    From evtools with MIT License 6 votes vote down vote up
def check_relationship(log, id):
    my_screen_name = get_screen_name(log)
    if my_screen_name == "Unknown":
        raise("Couldn't get my own screen name")
    log.debug("      Checking relationship of %s with me (%s)", id, my_screen_name)
    check_twitter_config()
    logging.captureWarnings(True)
    old_level = log.getEffectiveLevel()
    log.setLevel(logging.ERROR)
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    try:
        result = twitter.show_friendship(source_screen_name=my_screen_name, target_screen_name=id)
    except TwythonAuthError as e:
        log.setLevel(old_level)
        log.exception("   Problem trying to check relationship")
        twitter_auth_issue(e)
        raise
    except:
        raise
    log.setLevel(old_level)
    return result["relationship"]["source"]["following"], result["relationship"]["source"]["followed_by"] 
Example #8
Source File: tl_tweets.py    From evtools with MIT License 6 votes vote down vote up
def follow_twitter_user(log, id):
    log.debug("   Following %s", id)
    check_twitter_config()
    logging.captureWarnings(True)
    old_level = log.getEffectiveLevel()
    log.setLevel(logging.ERROR)
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    try:
        twitter.create_friendship(screen_name=id)
    except TwythonAuthError as e:
        log.setLevel(old_level)
        log.exception("   Problem trying to follow twitter user")
        twitter_auth_issue(e)
        raise
    except:
        raise
    log.setLevel(old_level) 
Example #9
Source File: tl_tweets.py    From evtools with MIT License 6 votes vote down vote up
def unfollow_twitter_user(log, id):
    log.debug("   Unfollowing %s", id)
    check_twitter_config()
    logging.captureWarnings(True)
    old_level = log.getEffectiveLevel()
    log.setLevel(logging.ERROR)
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    try:
        twitter.destroy_friendship(screen_name=id)
    except TwythonAuthError as e:
        log.setLevel(old_level)
        log.exception("Error unfollowing %s", id)
        twitter_auth_issue(e)
        raise
    except:
        log.exception("Error unfollowing %s", id)
    log.setLevel(old_level) 
Example #10
Source File: twitter.py    From advertools with MIT License 6 votes vote down vote up
def get_available_trends():
    """
    Returns the locations that Twitter has trending topic information for.

    https://developer.twitter.com/en/docs/trends/locations-with-trending-topics/api-reference/get-trends-available
    """
    twtr = Twython(**get_available_trends.get_auth_params())

    available_trends = twtr.get_available_trends()
    trends_df = pd.DataFrame(available_trends)
    trends_df['code'] = [x['code'] for x in trends_df['placeType']]
    trends_df['place_type'] = [x['name'] for x in trends_df['placeType']]
    del trends_df['placeType']
    trends_df = trends_df.sort_values(['country', 'place_type', 'name'])
    trends_df = trends_df.reset_index(drop=True)
    return trends_df 
Example #11
Source File: tl_tweets.py    From evtools with MIT License 6 votes vote down vote up
def get_screen_name(log):
    global MYSELF
    if not MYSELF or MYSELF == "Unknown":
        log.debug("   Getting current user screen name")
        check_twitter_config()
        logging.captureWarnings(True)
        old_level = log.getEffectiveLevel()
        log.setLevel(logging.ERROR)
        twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
        try:
            details = twitter.verify_credentials()
        except TwythonAuthError as e:
            log.setLevel(old_level)
            log.exception("   Problem trying to get screen name")
            twitter_auth_issue(e)
            raise
        except:
            log.exception("   Problem trying to get screen name")
            details = None
        log.setLevel(old_level)
        name = "Unknown"
        if details:
            name = details["screen_name"]
        MYSELF = name
    return MYSELF 
Example #12
Source File: util.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def add_access_token(creds_file=None):
    """
    For OAuth 2, retrieve an access token for an app and append it to a
    credentials file.
    """
    if creds_file is None:
        path = os.path.dirname(__file__)
        creds_file = os.path.join(path, 'credentials2.txt')
    oauth2 = credsfromfile(creds_file=creds_file)
    app_key = oauth2['app_key']
    app_secret = oauth2['app_secret']

    twitter = Twython(app_key, app_secret, oauth_version=2)
    access_token = twitter.obtain_access_token()
    tok = 'access_token={}\n'.format(access_token)
    with open(creds_file, 'a') as infile:
        print(tok, file=infile) 
Example #13
Source File: tl_tweets.py    From evtools with MIT License 5 votes vote down vote up
def get_following(log, id):
    log.debug("  Getting people %s is following", id)
    check_twitter_config()
    logging.captureWarnings(True)
    old_level = log.getEffectiveLevel()
    log.setLevel(logging.ERROR)
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    log.setLevel(old_level)

    cursor = -1
    max_loops = 15
    while cursor != 0:
        try:
            log.setLevel(logging.ERROR)
            following = twitter.get_friends_list(screen_name=id, cursor=cursor, count=200)
            log.setLevel(old_level)
        except TwythonAuthError as e:
            log.exception("   Problem trying to get people following")
            twitter_auth_issue(e)
            raise
        except:
            raise
        for u in following["users"]:
            yield u["screen_name"]
        cursor = following["next_cursor"]
        if cursor:
            s = random.randint(55, 65)
            log.debug("      Sleeping %ds to avoid rate limit. Cursor: %s", s, cursor)
            time.sleep(s)
        else:
            log.debug("      Normal query end")

        max_loops -= 1
        if max_loops <= 0:
            log.debug("      Killing search due to max loops")
            break
    log.setLevel(old_level) 
Example #14
Source File: tl_tweets.py    From evtools with MIT License 5 votes vote down vote up
def get_followers(log, id):
    log.debug("  Getting people following % s", id)
    check_twitter_config()
    logging.captureWarnings(True)
    old_level = log.getEffectiveLevel()
    log.setLevel(logging.ERROR)
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    log.setLevel(old_level)

    cursor = -1
    max_loops = 15
    while cursor != 0:
        try:
            log.setLevel(logging.ERROR)
            following = twitter.get_followers_list(screen_name=id, cursor=cursor, count=200)
            log.setLevel(old_level)
        except TwythonAuthError as e:
            log.exception("   Problem trying to get people following")
            twitter_auth_issue(e)
            raise
        except:
            raise
        for u in following["users"]:
            yield u
        cursor = following["next_cursor"]
        if cursor:
            s = random.randint(55, 65)
            log.debug("      Sleeping %ds to avoid rate limit. Cursor: %s", s, cursor)
            time.sleep(s)
        else:
            log.debug("      Normal query end")

        max_loops -= 1
        if max_loops <= 0:
            log.debug("      Killing search due to max loops")
            break
    log.setLevel(old_level) 
Example #15
Source File: tl_tweets.py    From evtools with MIT License 5 votes vote down vote up
def tweet_string(message, log, media=None):
    check_twitter_config()
    logging.captureWarnings(True)
    old_level = log.getEffectiveLevel()

    log.setLevel(logging.ERROR)
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

    retries = 0
    while retries < 2:
        log.setLevel(logging.ERROR)
        try:
            if media:
                photo = open(media, 'rb')
                media_ids = twitter.upload_media(media=photo)
                twitter.update_status(status=message.encode('utf-8').strip(), media_ids=media_ids['media_id'])
            else:
                twitter.update_status(status=message.encode('utf-8').strip())
            break
        except TwythonAuthError as e:
            log.setLevel(old_level)
            log.exception("   Problem trying to tweet string")
            twitter_auth_issue(e)
            return
        except:
            log.setLevel(old_level)
            log.exception("   Problem trying to tweet string")
        retries += 1
        s = random.randrange(5, 10 * retries)
        log.debug("   sleeping %d seconds for retry", s)
        time.sleep(s)

    log.setLevel(old_level)
    if retries == 5:
        log.error("Couldn't tweet string: %s with media: %s", message, media) 
Example #16
Source File: getting_data.py    From data-science-from-scratch with MIT License 5 votes vote down vote up
def call_twitter_search_api():

    twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET)

    # search for tweets containing the phrase "data science"
    for status in twitter.search(q='"data science"')["statuses"]:
        user = status["user"]["screen_name"].encode('utf-8')
        text = status["text"].encode('utf-8')
        print user, ":", text
        print 
Example #17
Source File: getting_data.py    From data-science-from-scratch with MIT License 5 votes vote down vote up
def call_twitter_search_api():

    twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET)

    # search for tweets containing the phrase "data science"
    for status in twitter.search(q='"data science"')["statuses"]:
        user = status["user"]["screen_name"].encode('utf-8')
        text = status["text"].encode('utf-8')
        print(user, ":", text)
        print() 
Example #18
Source File: twitter.py    From sneaky-creeper with MIT License 5 votes vote down vote up
def send(self, data):
        APP_KEY = self.param('sending', 'key')
        APP_SECRET = self.param('sending', 'secret')
        OAUTH_TOKEN = self.param('sending', 'token')
        OAUTH_TOKEN_SECRET = self.param('sending', 'tsecret')
        SCREEN_NAME = self.param('sending', 'name')

        twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
        twitter.update_status(status=data)

        return 
Example #19
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 #20
Source File: similarity.py    From ConvNetPy with MIT License 5 votes vote down vote up
def __init__(self):
        self.APP_KEY = "###"
        self.APP_SECRET = "###"

        self.twitter = Twython(self.APP_KEY, self.APP_SECRET, oauth_version=2)
        self.ACCESS_TOKEN = self.twitter.obtain_access_token()
        self.twitter = Twython(self.APP_KEY, access_token=self.ACCESS_TOKEN) 
Example #21
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 #22
Source File: cladi_plugin.py    From CLAtoolkit with GNU General Public License v3.0 5 votes vote down vote up
def perform_import(self, retrieval_param, unit):

        # Setup Twitter API Keys
        app_key = os.environ.get("TWITTER_APP_KEY")
        app_secret = os.environ.get("TWITTER_APP_SECRET")
        oauth_token = os.environ.get("TWITTER_OAUTH_TOKEN")
        oauth_token_secret = os.environ.get("TWITTER_OAUTH_TOKEN_SECRET")

        twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)

        count = 0
        next_max_id = None
        results = None
        while True:
            try:
                if count == 0:
                    results = twitter.search(q=retrieval_param,count=100, result_type='recent')
                else:
                    results = twitter.search(q=retrieval_param,count=100,max_id=next_max_id, result_type='recent')

                for tweet in results['statuses']:
                    self.insert_tweet(tweet, unit)

                if 'next_results' not in results['search_metadata']:
                        break
                else:
                    next_results_url_params = results['search_metadata']['next_results']
                    next_max_id = next_results_url_params.split('max_id=')[1].split('&')[0]
                count += 1
            except KeyError:
                    # When there are no more pages (['paging']['next']), break from the
                    # loop and end the script.
                    break 
Example #23
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 #24
Source File: twitterbot.py    From openplotter with GNU General Public License v2.0 5 votes vote down vote up
def send(self, tweetStr):
		self.tweetStr = tweetStr
		api = Twython(self._apiKey,self._apiSecret,self._accessToken,self._accessTokenSecret)
		api.update_status(status=self.tweetStr) 
Example #25
Source File: search.py    From twick with MIT License 5 votes vote down vote up
def __init__(self, credentials):
        self.twitter = twython.Twython(*credentials) 
Example #26
Source File: search.py    From twick with MIT License 5 votes vote down vote up
def query(self, q, **kw):
        opts = copy(defaults)
        opts.update(kw)
        wait = 1
        while True:
            try:
                response = Response(self.twitter.search(q=q, **opts))
                break
            except twython.exceptions.TwythonError as err:
                logger.info("Twython error: {0}".format(err))
                logger.info("Waiting {0} seconds...".format(wait))
                sleep(wait)
                wait *= 2
        return response 
Example #27
Source File: twitter.py    From Waveshare-E-Ink with MIT License 5 votes vote down vote up
def __init__(self):
    self._twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET) 
Example #28
Source File: twitter.py    From advertools with MIT License 5 votes vote down vote up
def get_application_rate_limit_status(consumed_only=True):
    """
    Returns the current rate limits for methods belonging to the
        specified resource families.

    :param consumed_only: Whether or not to return only items that
        have been consumed. Otherwise returns the full list.

    https://developer.twitter.com/en/docs/developer-utilities/rate-limit-status/api-reference/get-application-rate_limit_status
    """
    twtr = Twython(**get_application_rate_limit_status.get_auth_params())
    ratelimit = twtr.get_application_rate_limit_status()
    limit_df = pd.DataFrame()
    for resource in ratelimit['resources']:
        temp_df = pd.DataFrame(ratelimit['resources'][resource]).T
        limit_df = limit_df.append(temp_df, sort=False)
    limit_df['reset'] = pd.to_datetime(limit_df['reset'], unit='s')
    limit_df['resource'] = limit_df.index.str.split('/').str[1]
    limit_df.index.name = 'endpoint'
    limit_df = limit_df.sort_values(['resource'])
    limit_df = limit_df.reset_index()
    if consumed_only:
        print(' '*12, 'Rate limit as of:',
              pd.Timestamp.now(tz='UTC').strftime('%Y-%m-%-d %H:%M:%S'))
        return limit_df[limit_df['limit'].ne(limit_df['remaining'])]
    return limit_df 
Example #29
Source File: twitter.py    From advertools with MIT License 5 votes vote down vote up
def get_supported_languages():
    """
    Returns the list of languages supported by Twitter along with
        their ISO 639-1 code.

    https://developer.twitter.com/en/docs/developer-utilities/supported-languages/api-reference/get-help-languages
    """
    twtr = Twython(**get_supported_languages.get_auth_params())
    langs = twtr.get_supported_languages()
    return pd.DataFrame(langs) 
Example #30
Source File: single.py    From twip with MIT License 5 votes vote down vote up
def get_twitter():
    twitter = Twython(TWITTER_API_KEY, TWITTER_API_SECRET, oauth_version=2)
    return Twython(TWITTER_API_KEY, access_token=twitter.obtain_access_token())