Advertisement
J2897

Bitcoin Price TTS

Jan 4th, 2024 (edited)
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.19 KB | None | 0 0
  1. import requests
  2. import pyttsx3
  3. import time
  4. import logging
  5.  
  6. """
  7. Bitcoin Price TTS
  8.  
  9. This script continuously fetches the current Bitcoin price from the Binance public API and announces it
  10. using text-to-speech with a feminine voice. The RateLimiter class controls the request rate to adhere
  11. to any rate limits imposed by the API.
  12.  
  13. To run this script, be sure to install the required modules:
  14.  
  15.    1. requests: Used for making HTTP requests.
  16.       Install with: pip install requests
  17.  
  18.    2. pyttsx3: Text-to-speech library for Python.
  19.       Install with: pip install pyttsx3
  20.  
  21. Author: J2897 with help from ChatGPT.
  22. """
  23.  
  24. sleep_time = 30   # Adjust the sleep time as needed
  25. segmented = True  # Only say the price in $10 segments (less specific, but quieter during low volatility).
  26.  
  27. # Set up logging configuration to exclude INFO messages
  28. logging.basicConfig(level=logging.WARNING)
  29.  
  30. class RateLimiter:
  31.     def __init__(self, rate_limit):
  32.         """
  33.        Initializes the RateLimiter with a specified rate limit.
  34.        :param rate_limit: The time interval (in seconds) between consecutive requests.
  35.        """
  36.         self.rate_limit = rate_limit
  37.         self.last_request_time = 0
  38.     def wait(self):
  39.         """
  40.        Enforces rate limiting by pausing the execution if the time since the last request
  41.        is less than the specified rate limit.
  42.        """
  43.         current_time = time.time()
  44.         time_since_last_request = current_time - self.last_request_time
  45.         if time_since_last_request < self.rate_limit:
  46.             time.sleep(self.rate_limit - time_since_last_request)
  47.         self.last_request_time = time.time()
  48.  
  49. def get_bitcoin_price(rate_limiter):
  50.     """
  51.    Fetches the current Bitcoin price from the Binance public API.
  52.    :param rate_limiter: An instance of the RateLimiter class to control the request rate.
  53.    :return: The current Bitcoin price or None if an error occurs.
  54.    """
  55.     symbol = "BTCUSDT"
  56.     binance_api_url = f"https://api.binance.com/api/v3/ticker/price?symbol={symbol}"
  57.     try:
  58.         # Enforce rate limiting
  59.         rate_limiter.wait()
  60.         response = requests.get(binance_api_url)
  61.         response.raise_for_status()  # Raise an HTTPError for bad responses
  62.         data = response.json()
  63.         # Check if the response contains the required data
  64.         if 'symbol' in data and 'price' in data:
  65.             return float(data['price'])
  66.         else:
  67.             logging.ERROR("Unexpected data structure in the Binance ticker response.")
  68.             return None
  69.     except requests.exceptions.RequestException as err:
  70.         logging.ERROR(f"Request failed: {err}")
  71.         return None
  72.  
  73. def speak_price(price, voice_index=0):
  74.     """
  75.    Announces the Bitcoin price using text-to-speech.
  76.    :param price: The Bitcoin price to be announced.
  77.    :param voice_index: Index of the voice (default is 1, often a female voice).
  78.    """
  79.     engine = pyttsx3.init()
  80.     voices = engine.getProperty('voices')
  81.     if 0 <= voice_index < len(voices):
  82.         engine.setProperty('voice', voices[voice_index].id)
  83.     else:
  84.         logging.WARNING("Invalid voice index. Using the default voice.")
  85.     price_str = f"{int(price)}"
  86.     engine.say(price_str)
  87.     engine.runAndWait()
  88.  
  89. def main():
  90.     """
  91.    Main function to continuously fetch and announce the Bitcoin price.
  92.    """
  93.     rate_limiter = RateLimiter(rate_limit=1)  # Set a rate limit of 1 second for Binance
  94.     last_price = get_bitcoin_price(rate_limiter)  # Update last_price for the first iteration
  95.     while True:
  96.         current_price = get_bitcoin_price(rate_limiter)
  97.         if current_price is not None:
  98.             current_price_seg = int(current_price / 10)
  99.             last_price_seg = int(last_price / 10)
  100.             print(f"The current Bitcoin price is ${current_price:.2f}")
  101.             if segmented:
  102.                 if current_price_seg != last_price_seg:
  103.                     speak_price(current_price_seg * 10, voice_index=0)
  104.             else:
  105.                 speak_price(current_price, voice_index=1)
  106.             last_price = current_price  # Update last_price for the next iteration
  107.         time.sleep(sleep_time)
  108.  
  109. if __name__ == "__main__":
  110.     main()
  111.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement