Python tweepy.API Examples

The following are 30 code examples of tweepy.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 tweepy , or try the search function .
Example #1
Source File: twitter.py    From SecPi with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, id, params):
		super(Twitter, self).__init__(id, params)

		try:
			self.consumer_key = params["consumer_key"]
			self.consumer_secret = params["consumer_secret"]
			self.access_token = params["access_token"]
			self.access_token_secret = params["access_token_secret"]
			self.recipients = [rec.strip() for rec in params["recipients"].split(",")]
		except KeyError as ke:
			logging.error("Twitter: Error while trying to initialize notifier, it seems there is a config parameter missing: %s" % ke)
			self.corrupted = True
			return

		try:
			auth = tweepy.OAuthHandler(self.consumer_key, self.consumer_secret)
			auth.set_access_token(self.access_token, self.access_token_secret)

			self.api = tweepy.API(auth)
		except Exception as e:
			logging.error("Twitter: Error while trying to initialize notifier: %s" % e)
			self.corrupted = True
			return
			
		logging.info("Twitter: Notifier initialized") 
Example #2
Source File: twitter.py    From pajbot with MIT License 6 votes vote down vote up
def __init__(self, bot):
        self.bot = bot

        self.twitter_client = None
        self.listener = None

        if self.bot:
            self.bot.socket_manager.add_handler("twitter.follow", self.on_twitter_follow)
            self.bot.socket_manager.add_handler("twitter.unfollow", self.on_twitter_unfollow)

        if "twitter" not in bot.config:
            return

        twitter_config = bot.config["twitter"]
        self.use_twitter_stream = "streaming" in twitter_config and twitter_config["streaming"] == "1"

        try:
            self.twitter_auth = tweepy.OAuthHandler(twitter_config["consumer_key"], twitter_config["consumer_secret"])
            self.twitter_auth.set_access_token(twitter_config["access_token"], twitter_config["access_token_secret"])

            self.twitter_client = tweepy.API(self.twitter_auth)
        except:
            log.exception("Twitter authentication failed.")
            self.twitter_client = None 
Example #3
Source File: twitter.py    From CloudBot with GNU General Public License v3.0 6 votes vote down vote up
def twitter_url(match, conn):
    # Find the tweet ID from the URL
    tweet_id = match.group(1)

    # Get the tweet using the tweepy API
    tw_api = container.api
    if tw_api is None:
        return

    try:
        tweet = tw_api.get_status(tweet_id, tweet_mode=get_tweet_mode(conn))
    except tweepy.TweepError as e:
        if e.api_code in IGNORE_ERRORS:
            return

        raise

    user = tweet.user

    return format_tweet(tweet, user) 
Example #4
Source File: social.py    From THM-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
def last_tweet(self, ctx):
        # Secret twitter API key.
        creds = [cred.replace("\n", "") for cred in open(file_twitter_cred, "r")]

        # Auth & get.
        auth = tweepy.OAuthHandler(creds[0], creds[1])
        auth.set_access_token(creds[2], creds[3])
        api = tweepy.API(auth)
        tryhackme_tweets = api.user_timeline(
            screen_name='RealTryHackMe', count=20, include_rts=False)

        # Sends first found tweet. (and not reply.)
        for tweet in tryhackme_tweets:
            if not tweet.in_reply_to_screen_name:
                await ctx.send("https://twitter.com/RealTryHackMe/status/" + str(tweet.id))
                break 
Example #5
Source File: papersbot.py    From PapersBot with MIT License 6 votes vote down vote up
def getTwitterConfig(api):
    # Check for cached configuration, no more than a day old
    if os.path.isfile("twitter_config.dat"):
        mtime = os.stat("twitter_config.dat").st_mtime
        if time.time() - mtime < 24 * 60 * 60:
            with open("twitter_config.dat", "r") as f:
                return json.load(f)

    # Otherwise, query the Twitter API and cache the result
    config = api.configuration()
    with open("twitter_config.dat", "w") as f:
        json.dump(config, f)
    return config


# Read our list of feeds from file 
Example #6
Source File: api.py    From twitter_bot_utils with GNU General Public License v3.0 6 votes vote down vote up
def image_upload(self, filename, *args, **kwargs):
        """ :reference: https://dev.twitter.com/rest/reference/post/media/upload
            :allowed_param:
        """
        f = kwargs.pop('file', None)
        headers, post_data = API._pack_image(filename, self.max_size_standard, form_field='media', f=f)
        kwargs.update({'headers': headers, 'post_data': post_data})

        return bind_api(
            api=self,
            path='/media/upload.json',
            method='POST',
            payload_type='media',
            allowed_param=[],
            require_auth=True,
            upload_api=True
        )(*args, **kwargs) 
Example #7
Source File: client.py    From twitter-pandas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def me(self):
        """
        Returns a dataframe with just one row, which has all of the data avilable about the user tied to the API key.

        :return:
        """

        data = self.client.me()

        # page through it and parse results
        ds = [self._flatten_dict(data._json, layers=3, drop_deeper=True)]

        # form the dataframe
        df = pd.DataFrame(ds)

        return df

    # #################################################################
    # #####  Timeline Methods                                     #####
    # ################################################################# 
Example #8
Source File: client.py    From twitter-pandas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def saved_searches(self):
        """
        Returns saved search attributes for the user tied to the API keys,
        as a Pandas DataFrame that contains created_at, id, id_str, 
        name, position, query as columns

        :return:
        """

        data = self.client.saved_searches()

        ds = []

        # loop through SavedSearch objects return from the API
        for saved_search in data:
            # remove _api attribute
            saved_search.__dict__.pop('_api')
            # flatten the dictionary attribute of the object
            ds.append(self._flatten_dict(saved_search.__dict__, layers=3))

        # convert the flattened dictionaries to a dataframe
        df = pd.DataFrame(ds)

        return df 
Example #9
Source File: commands.py    From telegram-twitter-forwarder-bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
def cmd_verify(bot, update, args, chat):
    if not chat.twitter_request_token:
        bot.reply(update, "Use /auth command first")
        return
    if len(args) < 1:
        bot.reply(update, "No verifier code specified")
        return
    verifier_code = args[0]
    auth = OAuthHandler(bot.tw.auth.consumer_key, bot.tw.auth.consumer_secret)
    auth.request_token = json.loads(chat.twitter_request_token)
    try:
        auth.get_access_token(verifier_code)
    except TweepError:
        bot.reply(update, "Invalid verifier code. Use /auth again")
        return
    chat.twitter_token = auth.access_token
    chat.twitter_secret = auth.access_token_secret
    chat.save()
    bot.reply(update, "Access token setup complete")
    api = tweepy.API(auth)
    settings = api.get_settings()
    tz_name = settings.get("time_zone", {}).get("tzinfo_name")
    cmd_set_timezone(bot, update, [tz_name]) 
Example #10
Source File: client.py    From twitter-pandas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def exists_friendship(self, source_id=None, source_screen_name=None, target_id=None, target_screen_name=None):
        """
        Checks if a friendship exists between two users. Will return True if user_a follows user_b, otherwise False.

        :param source_id: Specifies the ID or screen name of the source user.
        :param source_screen_name: Specifies the screen name of the source user. Helpful for disambiguating when a valid screen name is also a user ID.
        :param target_id: Specifies the ID or screen name of the target user.
        :param target_screen_name: Specifies the screen name of the target user. Helpful for disambiguating when a valid screen name is also a user ID.
        :return:
        """

        # get friendship from the API
        data = self.retry_call(
            self.client.show_friendship,
            5,
            source_id=source_id,
            source_screen_name=source_screen_name,
            target_id=target_id,
            target_screen_name=target_screen_name
        )

        # return value of following attribute for user_a
        return data[0].following 
Example #11
Source File: monitor.py    From premeStock with MIT License 6 votes vote down vote up
def sendTweet(item,color,link, size):
    # line 102
    auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
    auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)
    api = tweepy.API(auth)

    tweet = item+"\n"
    tweet += color+'\n'
    tweet += size.title()+'\n'
    tweet += link+'\n'
    tweet += "Restock!"+'\n'
    tweet += str(datetime.utcnow().strftime('%H:%M:%S.%f')[:-3])

    try:
        api.update_status(tweet)
        print(tweet)
    except:
        print("Error sending tweet!") 
Example #12
Source File: client.py    From twitter-pandas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def favorites(self, id_=None, limit=None):
        """
        Returns a dataframe of all data about followers for the user tied to the API keys.

        :param id_: Specifies the ID or screen name of the user.
        :param limit: the maximum number of rows to return (optional, default None for all rows)
        :return:
        """

        # create a tweepy cursor to safely return the data
        curr = tweepy.Cursor(
            self.client.favorites,
            id_=id_,
        )

        # page through it and parse results
        ds = []
        for favorite in curr.items():
            # get the raw json, flatten it one layer and then discard anything nested farther
            ds.append(self._flatten_dict(favorite._json, layers=3, drop_deeper=True))

            if limit is not None:
                if len(ds) >= limit:
                    break

        # form the dataframe
        df = pd.DataFrame(ds)

        return df

    # #################################################################
    # #####  Saved Searches Methods                               #####
    # ################################################################# 
Example #13
Source File: client.py    From twitter-pandas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def friends(self, id_=None, user_id=None, screen_name=None, limit=None):
        """
        Returns a dataframe of all data about friends for the user tied to the API keys.

        :param id_: Specifies the ID or screen name of the user.
        :param user_id: Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
        :param screen_name: Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
        :param limit: the maximum number of rows to return (optional, default None for all rows)
        :return:
        """

        # create a tweepy cursor to safely return the data
        curr = tweepy.Cursor(
            self.client.friends_ids,
            id_=id_,
            user_id=user_id,
            screen_name=screen_name
        )

        # page through it and parse results
        df = None
        counter = 1
        for friend_id in curr.items():
            # get the raw json, flatten it one layer and then discard anything nested farther
            if df is None:
                df = self.get_user(user_id=friend_id)
            else:
                df.append(self.get_user(user_id=friend_id))

            if limit is not None:
                if counter >= limit:
                    break

            counter += 1

        return df 
Example #14
Source File: service.py    From polybot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def auth(self):
        auth = tweepy.OAuthHandler(
            self.config.get("twitter", "api_key"),
            self.config.get("twitter", "api_secret"),
        )
        auth.set_access_token(
            self.config.get("twitter", "access_key"),
            self.config.get("twitter", "access_secret"),
        )
        self.tweepy = tweepy.API(auth)
        me = self.tweepy.me()
        self.log.info("Connected to Twitter as %s", me.screen_name) 
Example #15
Source File: service.py    From polybot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup(self):
        print(
            "You'll need a consumer token and secret from your twitter app configuration here."
        )
        api_key = input("Consumer token: ")
        api_secret = input("Consumer secret: ")
        auth = tweepy.OAuthHandler(api_key, api_secret)
        try:
            redirect_url = auth.get_authorization_url()
        except tweepy.TweepError:
            print("Unable to fetch a request token! Check your consumer credentials")
            return False
        print(
            "OK, now visit this URL and get the verifier from there: %s" % redirect_url
        )
        verifier = input("Verifier: ")
        try:
            auth.get_access_token(verifier)
        except tweepy.TweepError:
            print(
                "Unable to fetch the access token! Verifier may not have been correct."
            )
            return False

        print("Checking everything works...")
        self.tweepy = tweepy.API(auth)
        print("Successfully authenticated as %s" % self.tweepy.me().screen_name)

        self.config.add_section("twitter")
        self.config.set("twitter", "api_key", api_key)
        self.config.set("twitter", "api_secret", api_secret)
        self.config.set("twitter", "access_key", auth.access_token)
        self.config.set("twitter", "access_secret", auth.access_token_secret)

        return True 
Example #16
Source File: client.py    From twitter-pandas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def followers(self, id_=None, user_id=None, screen_name=None, limit=None):
        """
        Returns a dataframe of all data about followers for the user tied to the API keys.

        :param id_: Specifies the ID or screen name of the user.
        :param user_id: Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
        :param screen_name: Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
        :param limit: the maximum number of rows to return (optional, default None for all rows)
        :return:
        """

        # create a tweepy cursor to safely return the data
        curr = tweepy.Cursor(
            self.client.followers,
            id_=id_,
            user_id=user_id,
            screen_name=screen_name
        )

        # page through it and parse results
        ds = []
        for follower in curr.items():
            # get the raw json, flatten it one layer and then discard anything nested farther
            ds.append(self._flatten_dict(follower._json, layers=3, drop_deeper=True))

            if limit is not None:
                if len(ds) >= limit:
                    break

        # form the dataframe
        df = pd.DataFrame(ds)

        return df 
Example #17
Source File: client.py    From twitter-pandas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_saved_search(self, id_):
        """
        Returns saved search attributes for one specific saved search object as a Pandas DataFrame
        that contains created_at, id, id_str, name, position, query as columns

        :param id_: Specifies the ID of the saved search object to convert to a DataFrame
        :return:
        """

        # get saved search from the API
        data = self.client.get_saved_search(id_)

        ds = []

        # remove _api attribute
        data.__dict__.pop('_api')

        # append single saved search
        ds.append(self._flatten_dict(data.__dict__))

        # convert a single SavedSearch object to a dataframe
        df = pd.DataFrame(ds)

        return df

    # #################################################################
    # #####  Direct Message Methods                               #####
    # ################################################################# 
Example #18
Source File: currency.py    From NanoTipBot with GNU General Public License v3.0 5 votes vote down vote up
def get_fiat_conversion(symbol, crypto_currency, fiat_amount):
    """
    Get the current fiat price conversion for the provided fiat:crypto pair
    """
    fiat = convert_symbol_to_fiat(symbol)
    if fiat == 'UNSUPPORTED':
        return -1
    fiat = fiat.lower()
    crypto_currency = crypto_currency.lower()
    post_url = 'https://api.coingecko.com/api/v3/coins/{}'.format(crypto_currency)
    try:
        # Retrieve price conversion from API
        response = requests.get(post_url)
        response_json = json.loads(response.text)
        price = Decimal(response_json['market_data']['current_price'][fiat])
        # Find value of 0.01 in the retrieved crypto
        penny_value = Decimal(0.01) / price
        # Find precise amount of the fiat amount in crypto
        precision = 1
        crypto_value = Decimal(fiat_amount) / price
        # Find the precision of 0.01 in crypto
        crypto_convert = precision * penny_value
        while Decimal(crypto_convert) < 1:
            precision *= 10
            crypto_convert = precision * penny_value
        # Round the expected amount to the nearest 0.01
        temp_convert = crypto_value * precision
        temp_convert = str(round(temp_convert))
        final_convert = Decimal(temp_convert) / Decimal(str(precision))

        return final_convert
    except Exception as e:
        logger.info("{}: Exception converting fiat price to crypto price".format(datetime.now()))
        logger.info("{}: {}".format(datetime.now(), e))
        raise e 
Example #19
Source File: client.py    From twitter-pandas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rate_limit_status(self):
        """
        Returns a dataframe with the rate limit status for all resources and endpoints in the API.

        :return:
        """

        data = self.client.rate_limit_status()

        ds = []
        for resource in data.get('resources', {}).keys():
            for endpoint in data.get('resources').get(resource).keys():
                ds.append({
                    'resource': resource,
                    'endpoint': endpoint,
                    'reset': data.get('resources').get(resource).get(endpoint).get('reset'),
                    'limit': data.get('resources').get(resource).get(endpoint).get('limit'),
                    'remaining': data.get('resources').get(resource).get(endpoint).get('remaining'),
                })

        df = pd.DataFrame(ds)

        df['reset'] = pd.to_datetime(df['reset'], unit='s')

        return df

    # #################################################################
    # #####  Trends Methods                                       #####
    # ################################################################# 
Example #20
Source File: twitter_id_converter.py    From discord-twitter-bot with MIT License 5 votes vote down vote up
def __init__(self, config, auth):
        self.config = config
        self.client = API(auth) 
Example #21
Source File: test_twitter.py    From discord-twitter-bot with MIT License 5 votes vote down vote up
def setUp(self):
        self.auth = tweepy.OAuthHandler(
            config["Twitter"]["consumer_key"], config["Twitter"]["consumer_secret"]
        )
        self.auth.set_access_token(
            config["Twitter"]["access_token"], config["Twitter"]["access_token_secret"]
        )
        self.client = tweepy.API(self.auth) 
Example #22
Source File: username_twitterdetails.py    From datasploit with GNU General Public License v3.0 5 votes vote down vote up
def output(data, username=""):
    if data[1] == "INVALID_API":
        print colored(
            style.BOLD + '\n[-] Twitter API Keys not configured. Skipping Twitter search.\nPlease refer to http://datasploit.readthedocs.io/en/latest/apiGeneration/.\n' + style.END, 'red')
    else:
        if data and data[0]:
            hashlist = data[0]['Hashtag Interactions']
            userlist = data[0]['User Interactions']
            userdetails = data[1]
            for k,v in userdetails.iteritems():
                try:
                    print k + ": " + str(v)
                except UnicodeEncodeError as e:
                    print colored(style.BOLD + '[!] Error: ' + str(e) + style.END, 'red')
            print "\n"
            count = Counter(hashlist).most_common()
            print "Top Hashtag Occurrence for user " + username + " based on last 1000 tweets"
            for hash, cnt in count:
                print "#" + hash + " : " + str(cnt)
            print "\n"

            # counting user occurrence
            countu = Counter(userlist).most_common()
            print "Top User Occurrence for user " + username + " based on last 1000 tweets"
            for usr, cnt in countu:
                print "@" + usr + " : " + str(cnt)
        else:
            print "No Associated Twitter account found." 
Example #23
Source File: vibration.py    From rpi-appliance-monitor with MIT License 5 votes vote down vote up
def tweet(msg):
    try:
        # Twitter is the only API that NEEDS something like a timestamp,
        # since it will reject identical tweets.
        tweet = msg + ' ' + strftime("%Y-%m-%d %H:%M:%S", localtime())
        auth = TweetHandler(twitter_api_key, twitter_api_secret)
        auth.set_access_token(twitter_access_token,
                              twitter_access_token_secret)
        tweepy.API(auth).update_status(status=tweet)
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        pass 
Example #24
Source File: accounts_post_2013.py    From twitterbots with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def start_streamer(api, account_queue, lookup_queue, query=None):
    """Starts a Tweet stream to find account information.

    Arguments:
        api {tweepy.API} -- The authenticated API instance.
    """
    l = StdOutListener(api, account_queue, lookup_queue)
    stream = Stream(api.auth, l)
    if query:
        stream.filter(track=[query])
    else:
        stream.sample() 
Example #25
Source File: accounts_pre_2013.py    From twitterbots with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    consumer_key = os.environ.get('TWEEPY_CONSUMER_KEY')
    consumer_secret = os.environ.get('TWEEPY_CONSUMER_SECRET')
    access_token = os.environ.get('TWEEPY_ACCESS_TOKEN')
    access_token_secret = os.environ.get('TWEEPY_ACCESS_TOKEN_SECRET')

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    api = tweepy.API(
        auth, wait_on_rate_limit_notify=True, wait_on_rate_limit=True)

    q = Queue()

    if len(sys.argv) < 3:
        print('Usage: python3 accounts_pre_2013.py min_id max_id')
        sys.exit()
    min_id = int(sys.argv[1])
    max_id = int(sys.argv[2])

    try:
        p = Process(
            target=fetch_accounts,
            args=[api, min_id, max_id, q],
            kwargs={'percentage': 5})
        p.start()
        while True:
            try:
                elem = q.get()
                print(elem)
            except Exception as e:
                print(e)
    except KeyboardInterrupt:
        print('\nCtrl+C detected. Shutting down...')
        p.terminate()
        p.join() 
Example #26
Source File: accounts_pre_2013.py    From twitterbots with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fetch_accounts(api,
                   account_queue,
                   min_id=DEFAULT_MIN_ID,
                   max_id=DEFAULT_MAX_ID,
                   percentage=DEFAULT_PERCENTAGE):
    """Fetches accounts from a min_id to a max_id.

    Arguments:
        api {tweepy.API} -- The authenticated API instance
        min_id {int} -- The starting account ID
        max_id {int} -- The maximum max ID
        queue {Queue} -- The queue to send found accounts to

    Keyword Arguments:
        percentage {int} -- The percentage of accounts between min_id and
            max_id to fetch (default: {100})
    """
    logger.info('Account enumeration service started')
    account_ids = []
    for i in range(min_id, max_id, 100):
        # Short-circuit for the common case
        sample = [uid for uid in range(i, i + 100)]
        if percentage != DEFAULT_PERCENTAGE:
            sample = random.sample(sample, percentage)
        account_ids.extend(sample)
        if len(account_ids) > 100:
            try:
                results = api.lookup_users(
                    user_ids=account_ids[0:100], include_entities=True)
            except Exception as e:
                logger.error(e)
            for result in results:
                user = result._json
                user['_tbsource'] = 'enum'
                account_queue.put(user)
            logger.debug('\t{} results found. Max ID: {}'.format(
                len(results), account_ids[100]))
            account_ids = account_ids[100:] 
Example #27
Source File: job.py    From tramcar with MIT License 5 votes vote down vote up
def send_tweet(self):
        sc = self.site.siteconfig
        if (not settings.DEBUG and sc.twitter_consumer_key and
                sc.twitter_consumer_secret and sc.twitter_access_token and
                sc.twitter_access_token_secret):
            auth = tweepy.OAuthHandler(
                       sc.twitter_consumer_key,
                       sc.twitter_consumer_secret
                   )
            auth.set_access_token(
                sc.twitter_access_token,
                sc.twitter_access_token_secret
            )

            api = tweepy.API(auth)

            if self.company.twitter:
                twitter = "@%s" % self.company.twitter
            else:
                twitter = self.company.name

            post = "[%s] %s at %s %s://%s/jobs/%s/" % (
                       self.format_country(),
                       self.title,
                       twitter,
                       sc.protocol,
                       self.site.domain,
                       self.id
                   )

            api.update_status(post) 
Example #28
Source File: models.py    From telegram-twitter-forwarder-bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
def tw_api(self, consumer_key, consumer_secret):
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(self.twitter_token, self.twitter_secret)
        return tweepy.API(auth) 
Example #29
Source File: services.py    From pythonjobs.ie with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
            self.consumer_key = settings.TWITTER_KEY
            self.consumer_secret = settings.TWITTER_SECRET
            self.token = settings.TWITTER_ACCESS_TOKEN
            self.token_secret = settings.TWITTER_TOKEN_SECRET
            auth = tweepy.OAuthHandler(self.consumer_key,
                                       self.consumer_secret)
            auth.set_access_token(self.token, self.token_secret)

            self.api = tweepy.API(auth) 
Example #30
Source File: currency.py    From NanoTipBot with GNU General Public License v3.0 5 votes vote down vote up
def get_fiat_price(fiat, crypto_currency):
    fiat = fiat.upper()
    crypto_currency = crypto_currency.upper()
    post_url = 'https://min-api.cryptocompare.com/data/price?fsym={}&tsyms={}'.format(crypto_currency, fiat)
    try:
        # Retrieve price conversion from API
        response = requests.get(post_url)
        response_json = json.loads(response.text)
        price = response_json['{}'.format(fiat)]

        return price
    except Exception as e:
        logger.info("{}: Exception converting fiat price to crypto price".format(datetime.now()))
        logger.info("{}: {}".format(datetime.now(), e))
        raise e