Advertisement
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
- import hashlib
- 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
- class VersionCheck:
- def __init__(self, url):
- self.url = url
- self.data = None
- self.values = []
- self.valid_versions = []
- self.current_version = None
- self.run()
- def fetch_latest(self):
- try:
- response = requests.get(self.url)
- response.raise_for_status()
- self.data = response.text
- except requests.exceptions.RequestException as err:
- print(f"Error fetching data: {err}")
- self.data = None
- def is_valid_version_number(self, version_number):
- # Check if the string is 32 characters long and only contains hexadecimal digits
- pattern = re.compile(r"^[0-9a-f]{32}$")
- return bool(pattern.match(version_number))
- def calculate_current_version(self):
- # Open the current script and calculate its version
- with open(__file__, 'rb') as f:
- md5 = hashlib.md5()
- while chunk := f.read(4096):
- md5.update(chunk)
- self.current_version = md5.hexdigest()
- def process_versions(self):
- if self.data is None:
- print("Unable to find current version number.")
- #sys.exit(1)
- self.values = [line.strip() for line in self.data.splitlines()]
- self.valid_versions = [value for value in self.values if self.is_valid_version_number(value)]
- if not self.valid_versions:
- print("No valid version numbers found.")
- #sys.exit(1)
- def compare_versions(self):
- # Calculate the current version
- self.calculate_current_version()
- # Print the latest version
- if self.values:
- pass
- #print(f"Latest Version Number {self.values[-1]}") # Print the latest version
- else:
- print("No data available")
- # Compare the current version to the latest version
- if self.is_valid_version_number(self.current_version) and self.valid_versions:
- if self.current_version == self.valid_versions[-1]:
- print("The current script version is up to date.")
- else:
- print(" The current script version is outdated.")
- print(f"Current script version: {self.current_version}")
- print(f"Latest version: {self.valid_versions[-1]}")
- else:
- print("Cannot compare versions.")
- def run(self):
- self.fetch_latest()
- self.process_versions()
- self.compare_versions()
- # Get the current OS language
- lang = locale.getdefaultlocale()[0]
- # Target streams
- STREAMS = [
- # Snooker 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",
- # Other streams.
- ]
- 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 ({} of {}) or {} to exit:"
- EXITING = "Exiting..."
- RETRYING = "retrying"
- INVALID_CHOICE = "Invalid choice. Please try again."
- AVAILABLE = "Available"
- OFFLINE = "offline"
- EXIT = "Exit"
- LOCAL_LANG = "Translate to"
- UPDATE_STREAMS_STATUS = "Update Stream Status "
- STRIP_FROM_TITLE = [
- "[",
- "Live",
- "broadcast",
- "]",
- "-",
- ]
- SORTBY_KEYWORDS = [
- "table",
- ]
- # Create a dictionary to store translations
- translations = {}
- def translate_text(text):
- if text not in translations:
- attempts = 0
- translator = GoogleTranslator(source='auto', target=lang.split('_')[0])
- while attempts < RETRY_COUNT:
- try:
- translations[text] = translator.translate(text)
- return translations[text]
- except Exception as e:
- attempts += 1
- if attempts < RETRY_COUNT:
- time.sleep(RETRY_DELAY)
- else:
- return f"Translation failed after {RETRY_COUNT} attempts. Please try again later."
- else:
- return translations[text]
- 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 = []
- translated_sortby_keywords = [translate_text(keyword) for keyword in SORTBY_KEYWORDS]
- for i, stream_url in enumerate(streams, start=1):
- title = get_stream_title(stream_url)
- for keyword in STRIP_FROM_TITLE:
- title = re.sub(rf'(?i){re.escape(keyword)}', '', title)
- keyword_matches = []
- for keyword in translated_sortby_keywords:
- match = re.search(rf'(?i)(-?)\s*{re.escape(keyword)}\s*(\d+)', title)
- if match:
- table_str = match.group(0)
- title = table_str + title[:match.start()] + title[match.end():]
- keyword_matches.append((keyword, int(match.group(2))))
- status = translate_text(AVAILABLE) if check_stream(stream_url) else translate_text(OFFLINE)
- menu.append((title.strip(), status, i, keyword_matches))
- def get_sort_key(x):
- event_name = x[0]
- for keyword, number in x[3]:
- event_name = re.sub(rf'(?i)({re.escape(keyword)})\s*\d+', '', event_name).strip()
- return (event_name.lower(), x[3])
- menu.sort(key=get_sort_key)
- return [(x[0], x[1], x[2]) for x in 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)}")
- available_count = 0
- for index, (title, status, original_index) in enumerate(menu, start=1):
- if status == translate_text(AVAILABLE):
- available_count += 1
- print(f"{available_count}. {title.strip()} - {status}")
- else:
- print(f" . {title.strip()} - {status}")
- print(f"{available_count+1}. {translate_text(EXIT)}")
- choice = input(f"{translate_text(ENTER_CHOICE).format(1, available_count, available_count+1)} ")
- if choice == str(available_count+1) or choice.lower() == translate_text(EXIT).lower():
- print(f"{translate_text(EXITING)}")
- break
- elif choice.isdigit() and 1 <= int(choice) <= available_count:
- available_index = 0
- for index, (title, status, original_index) in enumerate(menu, start=1):
- if status == translate_text(AVAILABLE):
- available_index += 1
- if available_index == int(choice):
- stream_url = STREAMS[menu[index-1][2] - 1]
- subprocess.run(['streamlink', f'--title={translate_text(menu[index-1][0])}', stream_url, 'best'])
- print(f"{translate_text(UPDATE_STREAMS_STATUS)}", end='', flush=True)
- for i, (title, status, original_index) in enumerate(menu):
- print(".", end='', flush=True)
- if original_index == menu[index-1][2]:
- new_status = translate_text(AVAILABLE) if check_stream(stream_url) else translate_text(OFFLINE)
- menu[i] = (title, new_status, original_index)
- print(f"\nDone.")
- time.sleep(4)
- os.system('cls' if os.name == 'nt' else 'clear')
- break
- else:
- print(translate_text(INVALID_CHOICE))
- def main():
- VersionCheck("https://pastebin.com/raw/bHvTgHht")
- 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__":
- if not check_dependencies():
- print("Please install the required dependencies and try again.")
- sys.exit(1)
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement