fixato creazione dei file config.json e requerement.txt nella folder del bot

This commit is contained in:
GiuDev 2025-02-08 16:21:48 +01:00
parent 44b8cd61ee
commit 5e20223d95
15 changed files with 293 additions and 402 deletions

View File

@ -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
```

View File

@ -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:

View File

@ -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):

View File

@ -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:

View File

@ -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:

View File

@ -426,7 +426,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()

View File

@ -1,93 +0,0 @@
{
"DEFAULT": {
"debug": false,
"log_file": "app.log",
"log_to_file": true,
"show_message": true,
"clean_console": true,
"root_path": "Video",
"movie_folder_name": "Movie",
"serie_folder_name": "Serie",
"anime_folder_name": "Anime",
"map_episode_name": "E%(episode)_%(episode_name)",
"config_qbit_tor": {
"host": "192.168.1.99",
"port": "7060",
"user": "admin",
"pass": "adminadmin"
},
"add_siteName": false,
"disable_searchDomain": false,
"not_close": false,
"telegram_bot": false
},
"REQUESTS": {
"timeout": 20,
"max_retry": 8,
"proxy_start_min": 0.1,
"proxy_start_max": 0.5
},
"M3U8_DOWNLOAD": {
"tqdm_delay": 0.01,
"default_video_workser": 12,
"default_audio_workser": 12,
"download_audio": true,
"merge_audio": true,
"specific_list_audio": [
"ita"
],
"download_subtitle": true,
"merge_subs": true,
"specific_list_subtitles": [
"eng",
"spa"
],
"cleanup_tmp_folder": true
},
"M3U8_CONVERSION": {
"use_codec": false,
"use_vcodec": true,
"use_acodec": true,
"use_bitrate": true,
"use_gpu": false,
"default_preset": "ultrafast"
},
"M3U8_PARSER": {
"force_resolution": -1,
"get_only_link": false
},
"SITE": {
"streamingcommunity": {
"domain": "paris"
},
"altadefinizionegratis": {
"domain": "pro"
},
"guardaserie": {
"domain": "meme"
},
"mostraguarda": {
"domain": "stream"
},
"ddlstreamitaly": {
"domain": "co",
"extra": {
"ips4_device_key": "",
"ips4_member_id": "",
"ips4_login_key": ""
}
},
"animeunity": {
"domain": "so"
},
"cb01new": {
"domain": "media"
},
"1337xx": {
"domain": "to"
},
"ilcorsaronero": {
"domain": "link"
}
}
}

View File

@ -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

View File

@ -1,16 +0,0 @@
httpx
bs4
rich
tqdm
m3u8
psutil
unidecode
jsbeautifier
pathvalidate
pycryptodomex
googlesearch-python
fake-useragent<2.0.0
qbittorrent-api
python-qbittorrent
Pillow
pyTelegramBotAPI

View File

@ -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.")

View File

@ -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
import threading
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"):
@ -140,7 +265,7 @@ class TelegramBot:
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()

View File

@ -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 = {}

View File

@ -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',

View File

@ -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)

View File

@ -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()