mirror of
https://github.com/Arrowar/StreamingCommunity.git
synced 2025-06-06 19:45:24 +00:00
Integration telegram (#251)
* sistemato il file telegram_bot.py come spiegato in chat, fatto un fix nel file session.py per l'aggiornamento del file script.json e sto caricando i file config.json e requerements.txt perchè vengono creati se non esistono quando si avvia il bot con python3 telegram_bot.py * sistemato il file telegram_bot.py come spiegato in chat, fatto un fix nel file session.py per l'aggiornamento del file script.json e sto caricando i file config.json e requerements.txt perchè vengono creati se non esistono quando si avvia il bot con python3 telegram_bot.py * fixato creazione dei file config.json e requerement.txt nella folder del bot
This commit is contained in:
parent
f3dbdffd52
commit
54567a8711
22
README.md
22
README.md
@ -501,12 +501,28 @@ The `run-container` command mounts also the `config.json` file, so any change to
|
||||
|
||||
## Configuration
|
||||
|
||||
You need to create an .env file and enter your Telegram token
|
||||
The bot was created to replace terminal commands and allow interaction via Telegram. Each download runs within a screen session, enabling multiple downloads to run simultaneously.
|
||||
|
||||
and user ID to authorize only one user to use it
|
||||
To run the bot in the background, simply start it inside a screen session and then press Ctrl + A, followed by D, to detach from the session without stopping the bot.
|
||||
|
||||
Command Functions:
|
||||
|
||||
🔹 /start – Starts a new search for a download. This command performs the same operations as manually running the script in the terminal with test_run.py.
|
||||
|
||||
🔹 /list – Displays the status of active downloads, with options to:
|
||||
|
||||
Stop an incorrect download using /stop <ID>.
|
||||
|
||||
View the real-time output of a download using /screen <ID>.
|
||||
|
||||
⚠ Warning: If a download is interrupted, incomplete files may remain in the folder specified in config.json. These files must be deleted manually to avoid storage or management issues.
|
||||
|
||||
🛠 Configuration: Currently, the bot's settings are stored in the config.json file, which is located in the same directory as the telegram_bot.py script.
|
||||
|
||||
## .env Example:
|
||||
|
||||
You need to create an .env file and enter your Telegram token and user ID to authorize only one user to use it
|
||||
|
||||
```
|
||||
TOKEN_TELEGRAM=IlTuo2131TOKEN$12D3Telegram
|
||||
AUTHORIZED_USER_ID=12345678
|
||||
@ -521,6 +537,8 @@ pip install -r requirements.txt
|
||||
|
||||
## On Linux/MacOS:
|
||||
|
||||
Start the bot from the folder /StreamingCommunity/TelegramHelp
|
||||
|
||||
```bash
|
||||
python3 telegram_bot.py
|
||||
```
|
||||
|
@ -8,9 +8,7 @@ from StreamingCommunity.Util.console import console
|
||||
from StreamingCommunity.Util.os import os_manager
|
||||
from StreamingCommunity.Util.message import start_message
|
||||
from StreamingCommunity.Lib.Downloader import HLS_Downloader
|
||||
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
|
||||
from StreamingCommunity.TelegramHelp.session import get_session, updateScriptId, deleteScriptId
|
||||
|
||||
from StreamingCommunity.TelegramHelp.telegram_bot import TelegramSession, get_bot_instance
|
||||
|
||||
# Logic class
|
||||
from StreamingCommunity.Api.Template.Class.SearchType import MediaItem
|
||||
@ -40,9 +38,9 @@ def download_film(select_title: MediaItem) -> str:
|
||||
bot.send_message(f"Download in corso:\n{select_title.name}", None)
|
||||
|
||||
# Get script_id
|
||||
script_id = get_session()
|
||||
script_id = TelegramSession.get_session()
|
||||
if script_id != "unknown":
|
||||
updateScriptId(script_id, select_title.name)
|
||||
TelegramSession.updateScriptId(script_id, select_title.name)
|
||||
|
||||
# Start message and display film information
|
||||
start_message()
|
||||
@ -68,9 +66,9 @@ def download_film(select_title: MediaItem) -> str:
|
||||
if TELEGRAM_BOT:
|
||||
|
||||
# Delete script_id
|
||||
script_id = get_session()
|
||||
script_id = TelegramSession.get_session()
|
||||
if script_id != "unknown":
|
||||
deleteScriptId(script_id)
|
||||
TelegramSession.deleteScriptId(script_id)
|
||||
|
||||
if "error" in r_proc.keys():
|
||||
try:
|
||||
|
@ -10,8 +10,7 @@ from StreamingCommunity.Util.console import console, msg
|
||||
from StreamingCommunity.Util.os import os_manager
|
||||
from StreamingCommunity.Util.message import start_message
|
||||
from StreamingCommunity.Lib.Downloader import MP4_downloader
|
||||
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
|
||||
from StreamingCommunity.TelegramHelp.session import get_session, updateScriptId, deleteScriptId
|
||||
from StreamingCommunity.TelegramHelp.telegram_bot import TelegramSession, get_bot_instance
|
||||
|
||||
|
||||
# Logic class
|
||||
@ -57,9 +56,9 @@ def download_episode(index_select: int, scrape_serie: ScrapeSerieAnime, video_so
|
||||
bot.send_message(f"Download in corso:\nTitolo:{scrape_serie.series_name}\nEpisodio: {obj_episode.number}", None)
|
||||
|
||||
# Get script_id
|
||||
script_id = get_session()
|
||||
script_id = TelegramSession.get_session()
|
||||
if script_id != "unknown":
|
||||
updateScriptId(script_id, f"{scrape_serie.series_name} - E{obj_episode.number}")
|
||||
TelegramSession.updateScriptId(script_id, f"{scrape_serie.series_name} - E{obj_episode.number}")
|
||||
|
||||
# Collect mp4 url
|
||||
video_source.get_embed(obj_episode.id)
|
||||
@ -147,9 +146,9 @@ def download_series(select_title: MediaItem):
|
||||
bot.send_message(f"Finito di scaricare tutte le serie e episodi", None)
|
||||
|
||||
# Get script_id
|
||||
script_id = get_session()
|
||||
script_id = TelegramSession.get_session()
|
||||
if script_id != "unknown":
|
||||
deleteScriptId(script_id)
|
||||
TelegramSession.deleteScriptId(script_id)
|
||||
|
||||
|
||||
def download_film(select_title: MediaItem):
|
||||
|
@ -8,8 +8,7 @@ from StreamingCommunity.Util.console import console
|
||||
from StreamingCommunity.Util.os import os_manager
|
||||
from StreamingCommunity.Util.message import start_message
|
||||
from StreamingCommunity.Lib.Downloader import HLS_Downloader
|
||||
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
|
||||
from StreamingCommunity.TelegramHelp.session import get_session, updateScriptId, deleteScriptId
|
||||
from StreamingCommunity.TelegramHelp.telegram_bot import TelegramSession, get_bot_instance
|
||||
|
||||
|
||||
# Logic class
|
||||
@ -43,9 +42,9 @@ def download_film(select_title: MediaItem) -> str:
|
||||
console.print(f"## Download: [red]{select_title.name} ##")
|
||||
|
||||
# Get script_id
|
||||
script_id = get_session()
|
||||
script_id = TelegramSession.get_session()
|
||||
if script_id != "unknown":
|
||||
updateScriptId(script_id, select_title.name)
|
||||
TelegramSession.updateScriptId(script_id, select_title.name)
|
||||
|
||||
# Start message and display film information
|
||||
start_message()
|
||||
@ -73,9 +72,9 @@ def download_film(select_title: MediaItem) -> str:
|
||||
if TELEGRAM_BOT:
|
||||
|
||||
# Delete script_id
|
||||
script_id = get_session()
|
||||
script_id = TelegramSession.get_session()
|
||||
if script_id != "unknown":
|
||||
deleteScriptId(script_id)
|
||||
TelegramSession.deleteScriptId(script_id)
|
||||
|
||||
if "error" in r_proc.keys():
|
||||
try:
|
||||
|
@ -10,9 +10,7 @@ from StreamingCommunity.Util.console import console, msg
|
||||
from StreamingCommunity.Util.message import start_message
|
||||
from StreamingCommunity.Util.table import TVShowManager
|
||||
from StreamingCommunity.Lib.Downloader import HLS_Downloader
|
||||
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
|
||||
from StreamingCommunity.TelegramHelp.session import get_session, updateScriptId, deleteScriptId
|
||||
|
||||
from StreamingCommunity.TelegramHelp.telegram_bot import TelegramSession, get_bot_instance
|
||||
|
||||
# Logic class
|
||||
from .util.ScrapeSerie import ScrapeSerie
|
||||
@ -58,9 +56,9 @@ def download_video(index_season_selected: int, index_episode_selected: int, scra
|
||||
)
|
||||
|
||||
# Get script_id and update it
|
||||
script_id = get_session()
|
||||
script_id = TelegramSession.get_session()
|
||||
if script_id != "unknown":
|
||||
updateScriptId(script_id, f"{scrape_serie.series_name} - S{index_season_selected} - E{index_episode_selected} - {obj_episode.name}")
|
||||
TelegramSession.updateScriptId(script_id, f"{scrape_serie.series_name} - S{index_season_selected} - E{index_episode_selected} - {obj_episode.name}")
|
||||
|
||||
# Define filename and path for the downloaded video
|
||||
mp4_name = f"{map_episode_title(scrape_serie.series_name, index_season_selected, index_episode_selected, obj_episode.name)}.mp4"
|
||||
@ -204,9 +202,9 @@ def download_series(select_season: MediaItem, version: str) -> None:
|
||||
bot.send_message(f"Finito di scaricare tutte le serie e episodi", None)
|
||||
|
||||
# Get script_id
|
||||
script_id = get_session()
|
||||
script_id = TelegramSession.get_session()
|
||||
if script_id != "unknown":
|
||||
deleteScriptId(script_id)
|
||||
TelegramSession.deleteScriptId(script_id)
|
||||
|
||||
|
||||
def display_episodes_list(scrape_serie) -> str:
|
||||
|
@ -422,7 +422,7 @@ class HLS_Downloader:
|
||||
'stopped': False
|
||||
}
|
||||
if TELEGRAM_BOT:
|
||||
bot.send_message(response)
|
||||
bot.send_message(f"Contenuto già scaricato!", None)
|
||||
return response
|
||||
|
||||
self.path_manager.setup_directories()
|
||||
|
@ -1,82 +0,0 @@
|
||||
# 04.02.25
|
||||
# Made by: @GiuPic
|
||||
|
||||
import json
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
class RequestManager:
|
||||
_instance = None
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
if not cls._instance:
|
||||
cls._instance = super().__new__(cls)
|
||||
return cls._instance
|
||||
|
||||
def __init__(self, json_file: str = "active_requests.json"):
|
||||
if not hasattr(self, 'initialized'):
|
||||
self.json_file = json_file
|
||||
self.initialized = True
|
||||
self.on_response_callback = None
|
||||
|
||||
def create_request(self, type: str) -> str:
|
||||
request_data = {
|
||||
"type": type,
|
||||
"response": None,
|
||||
"timestamp": time.time()
|
||||
}
|
||||
|
||||
with open(self.json_file, "w") as f:
|
||||
json.dump(request_data, f)
|
||||
|
||||
return "Ok"
|
||||
|
||||
def save_response(self, message_text: str) -> bool:
|
||||
try:
|
||||
# Carica il file JSON
|
||||
with open(self.json_file, "r") as f:
|
||||
data = json.load(f)
|
||||
|
||||
# Controlla se esiste la chiave 'type' e se la risposta è presente
|
||||
if "type" in data and "response" in data:
|
||||
data["response"] = message_text # Aggiorna la risposta
|
||||
|
||||
with open(self.json_file, "w") as f:
|
||||
json.dump(data, f, indent=4)
|
||||
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
except (FileNotFoundError, json.JSONDecodeError) as e:
|
||||
print(f"⚠️ save_response - errore: {e}")
|
||||
return False
|
||||
|
||||
def get_response(self) -> Optional[str]:
|
||||
try:
|
||||
with open(self.json_file, "r") as f:
|
||||
data = json.load(f)
|
||||
|
||||
# Verifica se esiste la chiave "response"
|
||||
if "response" in data:
|
||||
response = data["response"] # Ottieni la risposta direttamente
|
||||
|
||||
if response is not None and self.on_response_callback:
|
||||
self.on_response_callback(response)
|
||||
|
||||
return response
|
||||
|
||||
except (FileNotFoundError, json.JSONDecodeError) as e:
|
||||
print(f"get_response - errore: {e}")
|
||||
return None
|
||||
|
||||
def clear_file(self) -> bool:
|
||||
try:
|
||||
with open(self.json_file, "w") as f:
|
||||
json.dump({}, f)
|
||||
print(f"File {self.json_file} è stato svuotato con successo.")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"⚠️ clear_file - errore: {e}")
|
||||
return False
|
@ -1,56 +0,0 @@
|
||||
# 04.02.25
|
||||
# Made by: @GiuPic
|
||||
|
||||
import json
|
||||
|
||||
session_data = {}
|
||||
|
||||
def set_session(value):
|
||||
session_data['script_id'] = value
|
||||
|
||||
def get_session():
|
||||
return session_data.get('script_id', 'unknown')
|
||||
|
||||
def updateScriptId(screen_id, titolo):
|
||||
json_file = "scripts.json"
|
||||
try:
|
||||
with open(json_file, 'r') as f:
|
||||
scripts_data = json.load(f)
|
||||
except FileNotFoundError:
|
||||
scripts_data = []
|
||||
|
||||
# cerco lo script con lo screen_id
|
||||
for script in scripts_data:
|
||||
if script["screen_id"] == screen_id:
|
||||
# se trovo il match, aggiorno il titolo
|
||||
script["titolo"] = titolo
|
||||
|
||||
# aggiorno il file json
|
||||
with open(json_file, 'w') as f:
|
||||
json.dump(scripts_data, f, indent=4)
|
||||
|
||||
return
|
||||
|
||||
print(f"Screen_id {screen_id} non trovato.")
|
||||
|
||||
def deleteScriptId(screen_id):
|
||||
json_file = "scripts.json"
|
||||
try:
|
||||
with open(json_file, 'r') as f:
|
||||
scripts_data = json.load(f)
|
||||
except FileNotFoundError:
|
||||
scripts_data = []
|
||||
|
||||
for script in scripts_data:
|
||||
if script["screen_id"] == screen_id:
|
||||
# se trovo il match, elimino lo script
|
||||
scripts_data.remove(script)
|
||||
|
||||
# aggiorno il file json
|
||||
with open(json_file, 'w') as f:
|
||||
json.dump(scripts_data, f, indent=4)
|
||||
|
||||
print(f"Script eliminato per screen_id {screen_id}")
|
||||
return
|
||||
|
||||
print(f"Screen_id {screen_id} non trovato.")
|
@ -1,4 +1,4 @@
|
||||
# 04.02.25
|
||||
# 04.02.26
|
||||
# Made by: @GiuPic
|
||||
|
||||
import os
|
||||
@ -9,16 +9,141 @@ import uuid
|
||||
import json
|
||||
import threading
|
||||
import subprocess
|
||||
|
||||
import threading
|
||||
from typing import Optional
|
||||
|
||||
# External libraries
|
||||
import telebot
|
||||
|
||||
session_data = {}
|
||||
|
||||
# Fix import
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
|
||||
from StreamingCommunity.TelegramHelp.request_manager import RequestManager
|
||||
class TelegramSession:
|
||||
|
||||
def set_session(value):
|
||||
session_data['script_id'] = value
|
||||
|
||||
def get_session():
|
||||
return session_data.get('script_id', 'unknown')
|
||||
|
||||
def updateScriptId(screen_id, titolo):
|
||||
json_file = "../../scripts.json"
|
||||
try:
|
||||
with open(json_file, 'r') as f:
|
||||
scripts_data = json.load(f)
|
||||
except FileNotFoundError:
|
||||
scripts_data = []
|
||||
|
||||
# cerco lo script con lo screen_id
|
||||
for script in scripts_data:
|
||||
if script["screen_id"] == screen_id:
|
||||
# se trovo il match, aggiorno il titolo
|
||||
script["titolo"] = titolo
|
||||
|
||||
# aggiorno il file json
|
||||
with open(json_file, 'w') as f:
|
||||
json.dump(scripts_data, f, indent=4)
|
||||
|
||||
return
|
||||
|
||||
print(f"Screen_id {screen_id} non trovato.")
|
||||
|
||||
def deleteScriptId(screen_id):
|
||||
json_file = "../../scripts.json"
|
||||
try:
|
||||
with open(json_file, 'r') as f:
|
||||
scripts_data = json.load(f)
|
||||
except FileNotFoundError:
|
||||
scripts_data = []
|
||||
|
||||
for script in scripts_data:
|
||||
if script["screen_id"] == screen_id:
|
||||
# se trovo il match, elimino lo script
|
||||
scripts_data.remove(script)
|
||||
|
||||
# aggiorno il file json
|
||||
with open(json_file, 'w') as f:
|
||||
json.dump(scripts_data, f, indent=4)
|
||||
|
||||
print(f"Script eliminato per screen_id {screen_id}")
|
||||
return
|
||||
|
||||
print(f"Screen_id {screen_id} non trovato.")
|
||||
|
||||
class TelegramRequestManager:
|
||||
_instance = None
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
if not cls._instance:
|
||||
cls._instance = super().__new__(cls)
|
||||
return cls._instance
|
||||
|
||||
def __init__(self, json_file: str = "active_requests.json"):
|
||||
if not hasattr(self, 'initialized'):
|
||||
self.json_file = json_file
|
||||
self.initialized = True
|
||||
self.on_response_callback = None
|
||||
|
||||
def create_request(self, type: str) -> str:
|
||||
request_data = {
|
||||
"type": type,
|
||||
"response": None,
|
||||
"timestamp": time.time()
|
||||
}
|
||||
|
||||
with open(self.json_file, "w") as f:
|
||||
json.dump(request_data, f)
|
||||
|
||||
return "Ok"
|
||||
|
||||
def save_response(self, message_text: str) -> bool:
|
||||
try:
|
||||
# Carica il file JSON
|
||||
with open(self.json_file, "r") as f:
|
||||
data = json.load(f)
|
||||
|
||||
# Controlla se esiste la chiave 'type' e se la risposta è presente
|
||||
if "type" in data and "response" in data:
|
||||
data["response"] = message_text # Aggiorna la risposta
|
||||
|
||||
with open(self.json_file, "w") as f:
|
||||
json.dump(data, f, indent=4)
|
||||
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
except (FileNotFoundError, json.JSONDecodeError) as e:
|
||||
print(f"⚠️ save_response - errore: {e}")
|
||||
return False
|
||||
|
||||
def get_response(self) -> Optional[str]:
|
||||
try:
|
||||
with open(self.json_file, "r") as f:
|
||||
data = json.load(f)
|
||||
|
||||
# Verifica se esiste la chiave "response"
|
||||
if "response" in data:
|
||||
response = data["response"] # Ottieni la risposta direttamente
|
||||
|
||||
if response is not None and self.on_response_callback:
|
||||
self.on_response_callback(response)
|
||||
|
||||
return response
|
||||
|
||||
except (FileNotFoundError, json.JSONDecodeError) as e:
|
||||
print(f"get_response - errore: {e}")
|
||||
return None
|
||||
|
||||
def clear_file(self) -> bool:
|
||||
try:
|
||||
with open(self.json_file, "w") as f:
|
||||
json.dump({}, f)
|
||||
print(f"File {self.json_file} è stato svuotato con successo.")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"⚠️ clear_file - errore: {e}")
|
||||
return False
|
||||
|
||||
# Funzione per caricare variabili da un file .env
|
||||
def load_env(file_path="../../.env"):
|
||||
@ -44,13 +169,17 @@ class TelegramBot:
|
||||
if os.path.exists(cls._config_file):
|
||||
with open(cls._config_file, "r") as f:
|
||||
config = json.load(f)
|
||||
cls._instance = cls.init_bot(
|
||||
config["token"], config["authorized_user_id"]
|
||||
)
|
||||
|
||||
# Assicura che authorized_user_id venga trattato come una lista
|
||||
authorized_users = config.get('authorized_user_id', [])
|
||||
if isinstance(authorized_users, str):
|
||||
authorized_users = [int(uid) for uid in authorized_users.split(",") if uid.strip().isdigit()]
|
||||
|
||||
cls._instance = cls.init_bot(config['token'], authorized_users)
|
||||
#cls._instance = cls.init_bot(config['token'], config['authorized_user_id'])
|
||||
|
||||
else:
|
||||
raise Exception(
|
||||
"Bot non ancora inizializzato. Chiamare prima init_bot() con token e authorized_user_id"
|
||||
)
|
||||
raise Exception("Bot non ancora inizializzato. Chiamare prima init_bot() con token e authorized_user_id")
|
||||
return cls._instance
|
||||
|
||||
@classmethod
|
||||
@ -63,7 +192,8 @@ class TelegramBot:
|
||||
json.dump(config, f)
|
||||
return cls._instance
|
||||
|
||||
def __init__(self, token, authorized_user_id):
|
||||
def __init__(self, token, authorized_users):
|
||||
|
||||
def monitor_scripts():
|
||||
while True:
|
||||
try:
|
||||
@ -132,10 +262,10 @@ class TelegramBot:
|
||||
)
|
||||
|
||||
self.token = token
|
||||
self.authorized_user_id = authorized_user_id
|
||||
self.chat_id = authorized_user_id
|
||||
self.authorized_users = authorized_users
|
||||
self.chat_id = authorized_users
|
||||
self.bot = telebot.TeleBot(token)
|
||||
self.request_manager = RequestManager()
|
||||
self.request_manager = TelegramRequestManager()
|
||||
|
||||
# Registra gli handler
|
||||
self.register_handlers()
|
||||
@ -171,7 +301,7 @@ class TelegramBot:
|
||||
self.handle_response(message)
|
||||
|
||||
def is_authorized(self, user_id):
|
||||
return user_id == self.authorized_user_id
|
||||
return user_id in self.authorized_users
|
||||
|
||||
def handle_get_id(self, message):
|
||||
if not self.is_authorized(message.from_user.id):
|
||||
@ -194,7 +324,6 @@ class TelegramBot:
|
||||
|
||||
screen_id = str(uuid.uuid4())[:8]
|
||||
debug_mode = os.getenv("DEBUG")
|
||||
verbose = debug_mode
|
||||
|
||||
if debug_mode == "True":
|
||||
subprocess.Popen(["python3", "../../test_run.py", screen_id])
|
||||
@ -407,6 +536,13 @@ class TelegramBot:
|
||||
temp_file = f"/tmp/screen_output_{screen_id}.txt"
|
||||
|
||||
try:
|
||||
# Verifica se lo screen con l'ID specificato esiste
|
||||
existing_screens = subprocess.check_output(["screen", "-list"]).decode('utf-8')
|
||||
if screen_id not in existing_screens:
|
||||
print(f"⚠️ La sessione screen con ID {screen_id} non esiste.")
|
||||
self.bot.send_message(message.chat.id, f"⚠️ La sessione screen con ID {screen_id} non esiste.")
|
||||
return
|
||||
|
||||
# Cattura l'output della screen
|
||||
subprocess.run(
|
||||
["screen", "-X", "-S", screen_id, "hardcopy", "-h", temp_file],
|
||||
@ -440,51 +576,22 @@ class TelegramBot:
|
||||
"\n\n", "\n"
|
||||
) # Rimuovi newline multipli
|
||||
|
||||
# Estrarre tutte le parti da "Download:" fino a "Video" o "Subtitle", senza includerli
|
||||
download_matches = re.findall(
|
||||
r"Download: (.*?)(?:Video|Subtitle)", cleaned_output
|
||||
)
|
||||
if download_matches:
|
||||
# Serie TV e Film StreamingCommunity
|
||||
# Dentro cleaned_output c'è una stringa recupero quello che si trova tra ## ##
|
||||
download_section = re.search(r"##(.*?)##", cleaned_output, re.DOTALL)
|
||||
if download_section:
|
||||
cleaned_output_0 = "Download: " + download_section.group(1).strip()
|
||||
|
||||
proc_matches = re.findall(r"Proc: ([\d\.]+%)", cleaned_output)
|
||||
# Recupero tutto quello che viene dopo con ####
|
||||
download_section_bottom = re.search(r"####(.*)", cleaned_output, re.DOTALL)
|
||||
if download_section_bottom:
|
||||
cleaned_output_1 = download_section_bottom.group(1).strip()
|
||||
|
||||
# Creare una stringa unica con tutti i risultati
|
||||
result_string = "\n".join(
|
||||
[
|
||||
f"Download: {download_matches[i].strip()}\nDownload al {proc_matches[i]}"
|
||||
for i in range(len(download_matches))
|
||||
if i < len(proc_matches)
|
||||
]
|
||||
)
|
||||
|
||||
if result_string != "":
|
||||
cleaned_output = result_string
|
||||
else:
|
||||
print(f"❌ La parola 'Download:' non è stata trovata nella stringa.")
|
||||
else:
|
||||
|
||||
download_list = []
|
||||
|
||||
# Estrai tutte le righe che iniziano con "Download:" fino al prossimo "Download" o alla fine della riga
|
||||
matches = re.findall(r"Download:\s*(.*?)(?=Download|$)", cleaned_output)
|
||||
|
||||
# Se sono stati trovati download, stampali
|
||||
if matches:
|
||||
for i, match in enumerate(matches, 1):
|
||||
# rimuovo solo la parte "downloader.py:57Result:400" se esiste
|
||||
match = re.sub(r"downloader.py:\d+Result:400", "", match)
|
||||
match = match.strip() # Rimuovo gli spazi bianchi in eccesso
|
||||
if match: # Assicurati che la stringa non sia vuota
|
||||
print(f"Download {i}: {match}")
|
||||
|
||||
# Aggiungi il risultato modificato alla lista
|
||||
download_list.append(f"Download {i}: {match}")
|
||||
|
||||
# Creare una stringa unica con tutti i risultati
|
||||
cleaned_output = "\n".join(download_list)
|
||||
else:
|
||||
print("❌ Nessun download trovato")
|
||||
# Unico i due risultati se esistono
|
||||
if cleaned_output_0 and cleaned_output_1:
|
||||
cleaned_output = f"{cleaned_output_0}\n{cleaned_output_1}"
|
||||
# Rimuovo 'segments.py:302' e 'downloader.py:385' se presente
|
||||
cleaned_output = re.sub(r'downloader\.py:\d+', '', cleaned_output)
|
||||
cleaned_output = re.sub(r'segments\.py:\d+', '', cleaned_output)
|
||||
|
||||
# Invia l'output pulito
|
||||
print(f"📄 Output della screen {screen_id}:\n{cleaned_output}")
|
||||
@ -505,7 +612,16 @@ class TelegramBot:
|
||||
os.remove(temp_file)
|
||||
|
||||
def send_message(self, message, choices):
|
||||
if choices is None:
|
||||
|
||||
formatted_message = message
|
||||
if choices:
|
||||
formatted_choices = "\n".join(choices)
|
||||
formatted_message = f"{message}\n\n{formatted_choices}"
|
||||
|
||||
for chat_id in self.authorized_users:
|
||||
self.bot.send_message(chat_id, formatted_message)
|
||||
|
||||
""" if choices is None:
|
||||
if self.chat_id:
|
||||
print(f"{message}")
|
||||
self.bot.send_message(self.chat_id, message)
|
||||
@ -514,7 +630,7 @@ class TelegramBot:
|
||||
message = f"{message}\n\n{formatted_choices}"
|
||||
if self.chat_id:
|
||||
print(f"{message}")
|
||||
self.bot.send_message(self.chat_id, message)
|
||||
self.bot.send_message(self.chat_id, message) """
|
||||
|
||||
def _send_long_message(self, chat_id, text, chunk_size=4096):
|
||||
"""Suddivide e invia un messaggio troppo lungo in più parti."""
|
||||
@ -527,16 +643,20 @@ class TelegramBot:
|
||||
|
||||
if choices is None:
|
||||
print(f"{prompt_message}")
|
||||
self.bot.send_message(
|
||||
""" self.bot.send_message(
|
||||
self.chat_id,
|
||||
f"{prompt_message}",
|
||||
)
|
||||
) """
|
||||
for chat_id in self.authorized_users: # Manda a tutti gli ID autorizzati
|
||||
self.bot.send_message(chat_id, f"{prompt_message}")
|
||||
else:
|
||||
print(f"{prompt_message}\n\nOpzioni: {', '.join(choices)}")
|
||||
self.bot.send_message(
|
||||
""" self.bot.send_message(
|
||||
self.chat_id,
|
||||
f"{prompt_message}\n\nOpzioni: {', '.join(choices)}",
|
||||
)
|
||||
) """
|
||||
for chat_id in self.authorized_users: # Manda a tutti gli ID autorizzati
|
||||
self.bot.send_message(chat_id, f"{prompt_message}\n\nOpzioni: {', '.join(choices)}")
|
||||
|
||||
start_time = time.time()
|
||||
while time.time() - start_time < timeout:
|
||||
@ -546,7 +666,8 @@ class TelegramBot:
|
||||
time.sleep(1)
|
||||
|
||||
print(f"⚠️ Timeout: nessuna risposta ricevuta.")
|
||||
self.bot.send_message(self.chat_id, "⚠️ Timeout: nessuna risposta ricevuta.")
|
||||
for chat_id in self.authorized_users: # Manda a tutti gli ID autorizzati
|
||||
self.bot.send_message(chat_id, "⚠️ Timeout: nessuna risposta ricevuta.")
|
||||
self.request_manager.clear_file()
|
||||
return None
|
||||
|
||||
@ -559,3 +680,36 @@ class TelegramBot:
|
||||
|
||||
def get_bot_instance():
|
||||
return TelegramBot.get_instance()
|
||||
|
||||
# Esempio di utilizzo
|
||||
if __name__ == "__main__":
|
||||
|
||||
# Usa le variabili
|
||||
token = os.getenv("TOKEN_TELEGRAM")
|
||||
authorized_users = os.getenv("AUTHORIZED_USER_ID")
|
||||
|
||||
# Controlla se le variabili sono presenti
|
||||
if not token:
|
||||
print("Errore: TOKEN_TELEGRAM non è definito nel file .env.")
|
||||
sys.exit(1)
|
||||
|
||||
if not authorized_users:
|
||||
print("Errore: AUTHORIZED_USER_ID non è definito nel file .env.")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
TOKEN = token # Inserisci il token del tuo bot Telegram sul file .env
|
||||
AUTHORIZED_USER_ID = list(map(int, authorized_users.split(","))) # Inserisci il tuo ID utente Telegram sul file .env
|
||||
except ValueError as e:
|
||||
print(f"Errore nella conversione degli ID autorizzati: {e}. Controlla il file .env e assicurati che gli ID siano numeri interi separati da virgole.")
|
||||
sys.exit(1)
|
||||
|
||||
# Inizializza il bot
|
||||
bot = TelegramBot.init_bot(TOKEN, AUTHORIZED_USER_ID)
|
||||
bot.run()
|
||||
|
||||
"""
|
||||
start - Avvia lo script
|
||||
list - Lista script attivi
|
||||
get - Mostra ID utente Telegram
|
||||
"""
|
||||
|
@ -4,17 +4,18 @@ import os
|
||||
import sys
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, List
|
||||
|
||||
|
||||
class ConfigManager:
|
||||
def __init__(self, file_path: str = 'config.json') -> None:
|
||||
def __init__(self, file_name: str = 'config.json') -> None:
|
||||
"""Initialize the ConfigManager.
|
||||
|
||||
Parameters:
|
||||
- file_path (str, optional): The path to the configuration file. Default is 'config.json'.
|
||||
"""
|
||||
self.file_path = file_path
|
||||
self.file_path = Path(__file__).parent.parent.parent / file_name
|
||||
self.config = {}
|
||||
self.cache = {}
|
||||
|
||||
|
@ -13,6 +13,7 @@ import subprocess
|
||||
import contextlib
|
||||
import urllib.request
|
||||
import importlib.metadata
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# External library
|
||||
@ -452,6 +453,8 @@ class OsSummary:
|
||||
if not getattr(sys, 'frozen', False):
|
||||
requirements_file = 'requirements.txt'
|
||||
|
||||
requirements_file = Path(__file__).parent.parent.parent / requirements_file
|
||||
|
||||
if not os.path.exists(requirements_file):
|
||||
self.download_requirements(
|
||||
'https://raw.githubusercontent.com/Arrowar/StreamingCommunity/refs/heads/main/requirements.txt',
|
||||
|
@ -22,8 +22,7 @@ from StreamingCommunity.Util.logger import Logger
|
||||
|
||||
|
||||
# Telegram util
|
||||
from StreamingCommunity.TelegramHelp.session import get_session, deleteScriptId
|
||||
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
|
||||
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance, TelegramSession
|
||||
|
||||
|
||||
# Config
|
||||
@ -347,6 +346,6 @@ def main(script_id = 0):
|
||||
bot.send_message(f"Chiusura in corso", None)
|
||||
|
||||
# Delete script_id
|
||||
script_id = get_session()
|
||||
script_id = TelegramSession.get_session()
|
||||
if script_id != "unknown":
|
||||
deleteScriptId(script_id)
|
||||
TelegramSession.deleteScriptId(script_id)
|
||||
|
@ -3,19 +3,17 @@
|
||||
import sys
|
||||
from StreamingCommunity.run import main
|
||||
from StreamingCommunity.Util._jsonConfig import config_manager
|
||||
from StreamingCommunity.TelegramHelp.request_manager import RequestManager
|
||||
from StreamingCommunity.TelegramHelp.session import set_session
|
||||
from StreamingCommunity.TelegramHelp.telegram_bot import TelegramRequestManager, TelegramSession
|
||||
|
||||
# Svuoto il file
|
||||
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
|
||||
|
||||
if TELEGRAM_BOT:
|
||||
request_manager = RequestManager()
|
||||
request_manager = TelegramRequestManager()
|
||||
request_manager.clear_file()
|
||||
script_id = sys.argv[1] if len(sys.argv) > 1 else "unknown"
|
||||
|
||||
set_session(script_id)
|
||||
TelegramSession.set_session(script_id)
|
||||
main(script_id)
|
||||
|
||||
else:
|
||||
main()
|
Loading…
x
Reference in New Issue
Block a user