Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # save this file with a .py extension, run using using python from a command prompt > python filename.py
- import importlib
- import subprocess
- import os
- import sys
- import time
- import re
- import locale
- import random
- def check_dependencies():
- global BeautifulSoup, GoogleTranslator, requests
- # Check for Python packages
- required_packages = ['bs4', 'deep_translator', 'requests']
- print(f"Checking required packages {required_packages}")
- for package in required_packages:
- try:
- if package == 'bs4':
- bs4 = importlib.import_module(package)
- global BeautifulSoup
- BeautifulSoup = bs4.BeautifulSoup
- elif package == 'deep_translator':
- deep_translator = importlib.import_module(package)
- global GoogleTranslator
- GoogleTranslator = deep_translator.GoogleTranslator
- elif package == 'requests':
- global requests
- requests = importlib.import_module(package)
- except ImportError:
- print(f"Error: {package} is not installed. Please install it using pip: pip install {package}")
- return False
- # Check for streamlink binary
- print("Checking for streamlink binary")
- try:
- subprocess.run(['streamlink', '--version'], check=True, stdout=subprocess.DEVNULL)
- except FileNotFoundError:
- print("Error: streamlink is not installed. Please download and install it from https://streamlink.github.io/")
- return False
- # Check for VLC player
- print("Checking for VLC Player")
- vlc_path = None
- for path in os.environ['PATH'].split(os.pathsep):
- vlc_path = os.path.join(path, 'vlc.exe')
- if os.path.exists(vlc_path):
- break
- if vlc_path is None:
- print("Error: VLC player is not installed. Please download and install it from https://www.videolan.org/vlc/")
- return False
- return True
- if not check_dependencies():
- print("Please install the required dependencies and try again.")
- sys.exit(1)
- # Get the current OS language
- lang = locale.getdefaultlocale()[0]
- # Target streams
- STREAMS = [
- "https://www.huya.com/20072620",
- "https://www.huya.com/20072621",
- "https://www.huya.com/18501408",
- "https://www.huya.com/18501324",
- "https://www.huya.com/17455465",
- "https://www.huya.com/18501329",
- "https://www.huya.com/18501166",
- "https://www.huya.com/17611732",
- ]
- browser_headers = [
- {
- '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',
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
- 'Accept-Language': 'en-US,en;q=0.5',
- 'Accept-Encoding': 'gzip, deflate, br'
- },
- {
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
- 'Accept-Language': 'en-US,en;q=0.5',
- 'Accept-Encoding': 'gzip, deflate, br'
- },
- {
- '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',
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
- 'Accept-Language': 'en-US,en;q=0.5',
- 'Accept-Encoding': 'gzip, deflate, br'
- }
- ]
- RETRY_COUNT = 3
- RETRY_DELAY = 1
- # Text variables (English)
- GETTING_TITLE = "Getting title for stream : {}"
- TRANSLATING_TITLE = "Translating Title {} = {}"
- AVAILABLE_TABLES_STATUS = "Available Tables & Status."
- ENTER_CHOICE = "Enter your choice ({}-{}) or {} to exit:"
- EXITING = "Exiting..."
- RETRYING = "retrying"
- INVALID_CHOICE = "Invalid choice. Please try again."
- AVAILABLE = "Available"
- OFFLINE = "offline"
- EXIT = "Exit"
- LOCAL_LANG = "Translate to"
- def translate_text(text):
- attempts = 0
- translator = GoogleTranslator(source='auto', target=lang.split('_')[0])
- while attempts < RETRY_COUNT:
- try:
- return translator.translate(text)
- except Exception as e:
- attempts += 1
- if attempts < RETRY_COUNT:
- time.sleep(RETRY_DELAY)
- else:
- return f"Translation failed after {retries} attempts. Please try again later."
- def get_stream_title(stream_url: str) -> str:
- print(f"{translate_text(GETTING_TITLE).format(stream_url)} ", end='', flush=True)
- for _ in range(RETRY_COUNT):
- try:
- response = requests.get(stream_url, headers=BROWSER_HEADER)
- soup = BeautifulSoup(response.text, 'html.parser')
- title = soup.find('h2', id='J_roomTitle', class_='host-title')
- if title:
- text = title.text.strip()
- translator = GoogleTranslator(source='auto', target=lang.split('_')[0])
- translation = translator.translate(text)
- print(f"{translate_text(TRANSLATING_TITLE).format(text, translation)} ")
- return translation
- else:
- return ""
- except requests.exceptions.RequestException as e:
- print(f" {translate_text(RETRYING)} ")
- time.sleep(RETRY_DELAY)
- return ""
- def check_stream(stream_url: str) -> bool:
- try:
- output = subprocess.run(['streamlink', stream_url, 'best', '--stream-url'], capture_output=True, text=True)
- if output.returncode == 0:
- return True
- else:
- if "No playable streams found on this URL" in output.stdout:
- return False
- else:
- return False
- except FileNotFoundError:
- return False
- def build_stream_menu(streams: list) -> list:
- menu = []
- table_keyword = translate_text("table")
- for i, stream_url in enumerate(streams, start=1):
- title = get_stream_title(stream_url)
- title = title.replace(translate_text("[Live broadcast]"), "")
- match = re.search(rf'(?i)(-?)\s*{table_keyword}\s*(\d+)', title)
- if match:
- table_str = match.group(0).replace("-", "")
- title = table_str + title[:match.start()] + title[match.end():]
- status = translate_text(AVAILABLE) if check_stream(stream_url) else translate_text(OFFLINE)
- menu.append((title, status, i))
- 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')))
- return menu
- def display_menu(menu: list) -> None:
- os.system('cls' if os.name == 'nt' else 'clear')
- while True:
- print(f"{translate_text(AVAILABLE_TABLES_STATUS)}")
- for index, (title, status, original_index) in enumerate(menu, start=1):
- print(f"{index}. {title.strip()} - {status}")
- print(f"{index+1}. {translate_text(EXIT)}")
- choice = input(f"{translate_text(ENTER_CHOICE).format(1, index, index+1)} ")
- if choice == str(index+1) or choice.lower() == translate_text(EXIT).lower():
- print(f"{translate_text(EXITING)}")
- break
- elif choice.isdigit() and 1 <= int(choice) <= index:
- stream_url = STREAMS[menu[int(choice) - 1][2] - 1]
- subprocess.run(['streamlink', stream_url, 'best'])
- # delay before clearing so you can read output from streamlink.
- time.sleep(4)
- os.system('cls' if os.name == 'nt' else 'clear')
- else:
- print(translate_text(INVALID_CHOICE))
- def main():
- print(f"{translate_text(LOCAL_LANG)} [{lang}]")
- global BROWSER_HEADER
- BROWSER_HEADER = random.choice(browser_headers)
- print(f"Tonight Matthew I'm going to be\n {BROWSER_HEADER}\n")
- menu = build_stream_menu(STREAMS)
- display_menu(menu)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment