Guest User

Untitled

a guest
Feb 10th, 2025
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.95 KB | Source Code | 0 0
  1. # save this file with a .py extension, run using using python from a command prompt > python filename.py
  2.  
  3. import importlib
  4. import subprocess
  5. import os
  6. import sys
  7. import time
  8. import re
  9. import locale
  10. import random
  11.  
  12. def check_dependencies():
  13.     global BeautifulSoup, GoogleTranslator, requests
  14.  
  15.     # Check for Python packages
  16.     required_packages = ['bs4', 'deep_translator', 'requests']
  17.     print(f"Checking required packages {required_packages}")
  18.     for package in required_packages:
  19.         try:
  20.             if package == 'bs4':
  21.                 bs4 = importlib.import_module(package)
  22.                 global BeautifulSoup
  23.                 BeautifulSoup = bs4.BeautifulSoup
  24.             elif package == 'deep_translator':
  25.                 deep_translator = importlib.import_module(package)
  26.                 global GoogleTranslator
  27.                 GoogleTranslator = deep_translator.GoogleTranslator
  28.             elif package == 'requests':
  29.                 global requests
  30.                 requests = importlib.import_module(package)
  31.         except ImportError:
  32.             print(f"Error: {package} is not installed. Please install it using pip: pip install {package}")
  33.             return False
  34.  
  35.     # Check for streamlink binary
  36.     print("Checking for streamlink binary")
  37.     try:
  38.         subprocess.run(['streamlink', '--version'], check=True, stdout=subprocess.DEVNULL)
  39.     except FileNotFoundError:
  40.         print("Error: streamlink is not installed. Please download and install it from https://streamlink.github.io/")
  41.         return False
  42.  
  43.     # Check for VLC player
  44.     print("Checking for VLC Player")
  45.     vlc_path = None
  46.     for path in os.environ['PATH'].split(os.pathsep):
  47.         vlc_path = os.path.join(path, 'vlc.exe')
  48.         if os.path.exists(vlc_path):
  49.             break
  50.     if vlc_path is None:
  51.         print("Error: VLC player is not installed. Please download and install it from https://www.videolan.org/vlc/")
  52.         return False
  53.  
  54.     return True
  55.  
  56. if not check_dependencies():
  57.     print("Please install the required dependencies and try again.")
  58.     sys.exit(1)
  59.  
  60. # Get the current OS language
  61. lang = locale.getdefaultlocale()[0]
  62.  
  63. # Target streams
  64. STREAMS = [
  65.     "https://www.huya.com/20072620",
  66.     "https://www.huya.com/20072621",
  67.     "https://www.huya.com/18501408",
  68.     "https://www.huya.com/18501324",
  69.     "https://www.huya.com/17455465",
  70.     "https://www.huya.com/18501329",
  71.     "https://www.huya.com/18501166",
  72.     "https://www.huya.com/17611732",
  73. ]
  74.  
  75. browser_headers = [
  76.     {
  77.         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
  78.         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  79.         'Accept-Language': 'en-US,en;q=0.5',
  80.         'Accept-Encoding': 'gzip, deflate, br'
  81.     },
  82.     {
  83.         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
  84.         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  85.         'Accept-Language': 'en-US,en;q=0.5',
  86.         'Accept-Encoding': 'gzip, deflate, br'
  87.     },
  88.     {
  89.         'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
  90.         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  91.         'Accept-Language': 'en-US,en;q=0.5',
  92.         'Accept-Encoding': 'gzip, deflate, br'
  93.     }
  94. ]
  95.  
  96. RETRY_COUNT = 3
  97. RETRY_DELAY = 1
  98.  
  99. # Text variables (English)
  100. GETTING_TITLE = "Getting title for stream : {}"
  101. TRANSLATING_TITLE = "Translating Title {} = {}"
  102. AVAILABLE_TABLES_STATUS = "Available Tables & Status."
  103. ENTER_CHOICE = "Enter your choice ({}-{}) or {} to exit:"
  104. EXITING = "Exiting..."
  105. RETRYING = "retrying"
  106. INVALID_CHOICE = "Invalid choice. Please try again."
  107. AVAILABLE = "Available"
  108. OFFLINE = "offline"
  109. EXIT = "Exit"
  110. LOCAL_LANG = "Translate to"
  111.  
  112.  
  113. def translate_text(text):
  114.     attempts = 0
  115.     translator = GoogleTranslator(source='auto', target=lang.split('_')[0])
  116.     while attempts < RETRY_COUNT:
  117.         try:
  118.             return translator.translate(text)
  119.         except Exception as e:
  120.             attempts += 1
  121.             if attempts < RETRY_COUNT:
  122.                 time.sleep(RETRY_DELAY)
  123.             else:
  124.                 return f"Translation failed after {retries} attempts. Please try again later."
  125.  
  126. def get_stream_title(stream_url: str) -> str:
  127.     print(f"{translate_text(GETTING_TITLE).format(stream_url)} ", end='', flush=True)
  128.     for _ in range(RETRY_COUNT):  
  129.         try:
  130.             response = requests.get(stream_url, headers=BROWSER_HEADER)
  131.             soup = BeautifulSoup(response.text, 'html.parser')
  132.             title = soup.find('h2', id='J_roomTitle', class_='host-title')
  133.             if title:
  134.                 text = title.text.strip()
  135.                 translator = GoogleTranslator(source='auto', target=lang.split('_')[0])
  136.                 translation = translator.translate(text)
  137.                 print(f"{translate_text(TRANSLATING_TITLE).format(text, translation)} ")
  138.                 return translation
  139.             else:
  140.                 return ""
  141.         except requests.exceptions.RequestException as e:
  142.             print(f" {translate_text(RETRYING)} ")
  143.             time.sleep(RETRY_DELAY)  
  144.     return ""
  145.  
  146. def check_stream(stream_url: str) -> bool:
  147.     try:
  148.         output = subprocess.run(['streamlink', stream_url, 'best', '--stream-url'], capture_output=True, text=True)
  149.         if output.returncode == 0:
  150.             return True
  151.         else:
  152.             if "No playable streams found on this URL" in output.stdout:
  153.                 return False
  154.             else:
  155.                 return False
  156.     except FileNotFoundError:
  157.         return False
  158.  
  159. def build_stream_menu(streams: list) -> list:
  160.     menu = []
  161.     table_keyword = translate_text("table")
  162.     for i, stream_url in enumerate(streams, start=1):
  163.         title = get_stream_title(stream_url)
  164.         title = title.replace(translate_text("[Live broadcast]"), "")
  165.         match = re.search(rf'(?i)(-?)\s*{table_keyword}\s*(\d+)', title)
  166.         if match:
  167.             table_str = match.group(0).replace("-", "")
  168.             title = table_str + title[:match.start()] + title[match.end():]
  169.  
  170.         status = translate_text(AVAILABLE) if check_stream(stream_url) else translate_text(OFFLINE)
  171.         menu.append((title, status, i))
  172.     menu.sort(key=lambda x: (re.sub(rf'(?i){table_keyword}\s*\d+', '', x[0]).lower(), int(re.search(rf'(?i){table_keyword}\s*(\d+)', x[0]).group(1)) if re.search(rf'(?i){table_keyword}\s*(\d+)', x[0]) else float('inf')))
  173.     return menu
  174.  
  175. def display_menu(menu: list) -> None:
  176.     os.system('cls' if os.name == 'nt' else 'clear')
  177.     while True:
  178.         print(f"{translate_text(AVAILABLE_TABLES_STATUS)}")
  179.         for index, (title, status, original_index) in enumerate(menu, start=1):
  180.             print(f"{index}. {title.strip()} - {status}")
  181.         print(f"{index+1}. {translate_text(EXIT)}")
  182.         choice = input(f"{translate_text(ENTER_CHOICE).format(1, index, index+1)} ")
  183.         if choice == str(index+1) or choice.lower() == translate_text(EXIT).lower():
  184.             print(f"{translate_text(EXITING)}")
  185.             break
  186.         elif choice.isdigit() and 1 <= int(choice) <= index:
  187.             stream_url = STREAMS[menu[int(choice) - 1][2] - 1]
  188.             subprocess.run(['streamlink', stream_url, 'best'])
  189.             # delay before clearing so you can read output from streamlink.
  190.             time.sleep(4)
  191.             os.system('cls' if os.name == 'nt' else 'clear')
  192.         else:
  193.             print(translate_text(INVALID_CHOICE))
  194.  
  195. def main():
  196.     print(f"{translate_text(LOCAL_LANG)} [{lang}]")
  197.     global BROWSER_HEADER
  198.     BROWSER_HEADER = random.choice(browser_headers)
  199.     print(f"Tonight Matthew I'm going to be\n {BROWSER_HEADER}\n")
  200.     menu = build_stream_menu(STREAMS)
  201.     display_menu(menu)
  202.  
  203. if __name__ == "__main__":
  204.     main()
  205.  
Advertisement
Add Comment
Please, Sign In to add comment