def kill_script(script_name, token_name, folder=None):
"""
Kills the specified Python script and returns its absolute path.
code
Assistant
Args:
script_name (str): The name of the script to kill (e.g., 'myscript.py').
token_name (str): The token associated with the script.
folder (str, optional): The directory where the script is located. Defaults to None.
Returns:
str: A message indicating the result of the kill operation.
"""
killed_paths = []
try:
# Iterate over all running processes
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
try:
# Check if the process is a Python 3 process running the specified script
if (proc.info['cmdline'] and
'python3' in proc.info['cmdline'][0] and
any(script_name in arg for arg in proc.info['cmdline'][1:])):
# Extract the script path from command line arguments
script_path = next(arg for arg in proc.info['cmdline'][1:] if script_name in arg)
# Construct absolute path
if folder:
absolute_path = os.path.abspath(os.path.join(folder, script_path))
else:
absolute_path = os.path.abspath(script_path)
# Append to the list before killing
killed_paths.append(absolute_path)
# Terminate the process
proc.terminate()
try:
proc.wait(timeout=5) # Wait for termination
except psutil.TimeoutExpired:
proc.kill() # Force kill if not terminated
except (psutil.NoSuchProcess, psutil.AccessDenied, StopIteration):
# Handle processes that have terminated or inaccessible
continue
if killed_paths:
paths_str = "\n".join(killed_paths)
return f"The following scripts for token \"{token_name}\" were killed successfully:\n{paths_str}"
else:
return f"No running process found for {script_name} with token \"{token_name}\"."
except Exception as e:
return f"An error occurred while attempting to kill {script_name} for token \"{token_name}\": {str(e)}"
def get_current_token_set(context):
with open("WhichSet.json", "r") as file:
which_set_data = json.load(file)
current_set = int(which_set_data["Set"])
return current_set
def update_current_set(set_number):
with open("WhichSet.json", "w") as file:
json.dump({"Set": str(set_number)}, file)
import os
import subprocess
import logging
import sys
def start_script(script_name, token_name, folder=None, arguments=None, venv_name=None, env_type='venv'):
"""
Starts a Python script in a new gnome-terminal with detailed logging and interactive prompts.
code
Parameters:
script_name (str): The name of the script to execute.
token_name (str): A descriptive name for the script/token.
folder (str, optional): The directory where the script is located. Defaults to None.
arguments (list, optional): A list of arguments to pass to the script. Defaults to None.
venv_name (str, optional): The name/path of the virtual environment to activate. Defaults to None.
env_type (str, optional): Type of the environment ('venv' or 'conda'). Defaults to 'venv'.
Returns:
str: Success or error message.
"""
# Configure logging
logger = logging.getLogger('start_script')
logger.setLevel(logging.INFO)
# Clear existing handlers to avoid duplicate logs
if logger.hasHandlers():
logger.handlers.clear()
# Define log format with an extra newline for better readability
if COLORAMA_AVAILABLE:
LOG_FORMAT = '%(levelname_color)s%(levelname)s%(reset)s: %(message)s\n'
else:
LOG_FORMAT = '[%(levelname)s] %(message)s\n'
class ColorFormatter(logging.Formatter):
def format(self, record):
if COLORAMA_AVAILABLE:
level_colors = {
'INFO': Fore.GREEN,
'ERROR': Fore.RED,
'WARNING': Fore.YELLOW,
'DEBUG': Fore.CYAN,
}
level_color = level_colors.get(record.levelname, Fore.WHITE)
record.levelname_color = level_color
record.reset = Style.RESET_ALL
return super().format(record)
formatter = ColorFormatter(LOG_FORMAT)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)
try:
logger.info(f"Initializing start_script for token: {token_name}")
# Validate folder if provided
if folder:
logger.info(f"Checking if folder '{folder}' exists.")
if not os.path.isdir(folder):
error_msg = f"Folder '{folder}' does not exist."
logger.error(error_msg)
return error_msg
else:
logger.info(f"Folder '{folder}' exists.")
# Determine environment activation and deactivation commands
if venv_name:
if env_type.lower() == 'conda':
activate_cmd = f"conda activate {venv_name}"
deactivate_cmd = "conda deactivate"
else: # assume virtualenv
activate_cmd = f"source {venv_name}/bin/activate"
deactivate_cmd = "deactivate"
logger.info(f"Environment type detected: {env_type}")
logger.info(f"Activation command: {activate_cmd}")
logger.info(f"Deactivation command: {deactivate_cmd}")
else:
activate_cmd = ""
deactivate_cmd = ""
logger.info("No virtual environment specified.")
# Construct the command to run in the new terminal
command_parts = []
if folder:
# Change directory
command_parts.append(f'echo "🔄 Changing directory to {folder}"')
command_parts.append(f'cd "{folder}"')
command_parts.append('echo "✅ Changed directory."')
#command_parts.append('read -p "➡️ Press Enter to continue..."')
if activate_cmd:
# Activate virtual environment
command_parts.append(f'echo "🔌 Activating virtual environment: {venv_name}"')
command_parts.append(f'{activate_cmd}')
command_parts.append('echo "✅ Virtual environment activated."')
#command_parts.append('read -p "➡️ Press Enter to continue..."')
# Prepare the script execution command
script_path = f"./{script_name}" if folder else script_name
args = " ".join([str(arg) for arg in arguments]) if arguments else ""
full_script_cmd = f'echo "▶️ Running script: python3 {script_path} {args}" && python3 "{script_path}" {args}'
command_parts.append(full_script_cmd)
command_parts.append('echo "✅ Script execution completed."')
#command_parts.append('read -p "➡️ Press Enter to continue..."')
if deactivate_cmd:
# Deactivate virtual environment
command_parts.append(f'echo "🔌 Deactivating virtual environment."')
command_parts.append(f'{deactivate_cmd}')
command_parts.append('echo "✅ Virtual environment deactivated."')
#command_parts.append('read -p "➡️ Press Enter to continue..."')
# Final message before closing
command_parts.append('echo "🎉 All steps completed. Press Enter to close the terminal."')
# Combine all commands with '&&' to ensure sequential execution
terminal_command = ' && '.join(command_parts)
logger.info(f"Constructed terminal command: {terminal_command}")
# Open a new gnome-terminal and execute the command
subprocess.call([
'gnome-terminal',
'--',
'bash',
'-c',
terminal_command
])
success_msg = f"🚀 '{token_name}' started in a new terminal window successfully."
logger.info(success_msg)
return success_msg
except Exception as e:
error_msg = f"❌ Failed to start '{token_name}' in a new terminal window: {e}"
logger.error(error_msg)
return error_msg
def start(update: Update, context: CallbackContext):
global PASSWORD_REQUIRED
if PASSWORD_REQUIRED:
update.message.reply_text("PLEASE ENTER PASSWORD")
return ASK_PASSWORD
else:
return dashboard(update, context)
def toggle_script_a1(update: Update, context: CallbackContext):
"""Toggle the Text Send script ON/OFF."""
query = update.callback_query
query.answer()
code
# Step 1: Retrieve Current Set
current_set = get_current_token_set(context)
if current_set is None:
context.bot.send_message(chat_id=query.message.chat_id, text="Error: Unable to retrieve current set.")
return dashboard(query, context)
# Step 2: Dynamically Retrieve Script Name and Token Name
script_name = get_send_script_name(current_set)
token_name = get_current_token(current_set) # Corrected
if token_name is None:
context.bot.send_message(chat_id=query.message.chat_id, text="Error: Unable to retrieve token name.")
return dashboard(query, context)
# Step 3: Determine the Folder (use the current working directory)
folder = os.getcwd()
# Step 4: Check if the script is running
if is_script_running(script_name):
# Step 5: Kill the script if it's running
message = kill_script(script_name, token_name) # Removed 'folder'
else:
# Optionally, pass arguments if needed
arguments = [str(current_set)]
message = start_script(script_name, token_name, folder, arguments=arguments)
# Step 6: Send Response Back to User
context.bot.send_message(chat_id=query.message.chat_id, text=message)
return dashboard(query, context)
def new_script4_action(update: Update, context):
query = update.callback_query
query.answer()
context.bot.send_message(chat_id=query.message.chat_id, text="Please provide the new target group link:")
return ASK_LINK
def new_script5_action(update: Update, context):
query = update.callback_query
query.answer()
context.bot.send_message(chat_id=query.message.chat_id, text="Please provide the token:")
return ASK_TOKEN
def change_min_max_time_action(update: Update, context):
query = update.callback_query
query.answer()
context.bot.send_message(chat_id=query.message.chat_id, text="Please provide the new min_time and max_time values separated by a space:")
return ASK_MIN_MAX_TIME
def handle_min_max_time_input(update: Update, context):
values = update.message.text.split()
if len(values) == 2:
min_time, max_time = values
current_set = get_current_token_set(context)
change_message = change_time_values(min_time, max_time, current_set)
context.bot.send_message(chat_id=update.message.chat_id, text=change_message)
else:
context.bot.send_message(chat_id=update.message.chat_id, text="Invalid input. Please provide min_time and max_time values separated by a space.")
return dashboard(update, context)
def change_image_count_action(update: Update, context):
query = update.callback_query
query.answer()
context.bot.send_message(chat_id=query.message.chat_id, text="Please provide the new image count (default is 250):")
return ASK_IMAGE_COUNT
def change_sticker_count_action(update: Update, context):
query = update.callback_query
query.answer()
context.bot.send_message(chat_id=query.message.chat_id, text="Please provide the new sticker count (default is 200):")
return ASK_STICKER_COUNT
def change_long_command_count_action(update: Update, context):
query = update.callback_query
query.answer()
context.bot.send_message(chat_id=query.message.chat_id, text="Please provide the new long command count (default is 1):")
return ASK_LONG_COMMAND_COUNT
def change_meme_pump_command_count_action(update: Update, context):
query = update.callback_query
query.answer()
context.bot.send_message(chat_id=query.message.chat_id, text="Please provide the new meme pump command count between 0 and 1 (default is 0.3):")
return ASK_MEME_PUMP_COMMAND_COUNT
🚀 'Nick' started in a new terminal window successfully.
EVEN WHEN THE SCRIPT CRASHES, I ONLY WANT TO GET THAT OUTPUT IF THE SCRIPT STAYS ALIVE, HOW CAN WE DO THAT?
To ensure that your Telegram bot only sends a success message when the script remains running (i.e., doesn't crash immediately), you need to modify the start_script function. The current implementation assumes that the script starts successfully without verifying its status after initiation. Here's how you can adjust the function to achieve the desired behavior:
Use subprocess.Popen Instead of subprocess.call:
subprocess.call is synchronous and waits for the command to complete, which isn't ideal for launching scripts in new terminals where you want the bot to remain responsive.
subprocess.Popen allows you to start the process asynchronously, enabling the bot to continue running and perform checks after launching the script.
Implement a Verification Mechanism:
After launching the script, introduce a short delay to give the script time to initialize.
Use the is_script_running function to verify if the script is actively running.
Based on this verification, send either a success or failure message to the user.
Handle Potential Race Conditions:
Ensure that the delay is sufficient for the script to start but not too long to cause unnecessary waiting.
Consider using threading or asynchronous programming if you anticipate multiple rapid requests, though for simplicity, a short sleep should suffice.
Modified start_script Function
Here's the updated start_script function incorporating the above changes:
python
import subprocess
import json
import os
import psutil
import time
import logging
import sys
try:
from colorama import Fore, Style, init
COLORAMA_AVAILABLE = True
init(autoreset=True) # Initialize colorama
except ImportError:
COLORAMA_AVAILABLE = False
def start_script(script_name, token_name, folder=None, arguments=None, venv_name=None, env_type='venv'):
"""
Starts a Python script in a new gnome-terminal with detailed logging and interactive prompts.
Verifies if the script is running after initiation.
Parameters:
script_name (str): The name of the script to execute.
token_name (str): A descriptive name for the script/token.
folder (str, optional): The directory where the script is located. Defaults to None.
arguments (list, optional): A list of arguments to pass to the script. Defaults to None.
venv_name (str, optional): The name/path of the virtual environment to activate. Defaults to None.
env_type (str, optional): Type of the environment ('venv' or 'conda'). Defaults to 'venv'.
Returns:
str: Success or error message based on script status.
"""
# Configure logging
logger = logging.getLogger('start_script')
logger.setLevel(logging.INFO)
# Clear existing handlers to avoid duplicate logs
if logger.hasHandlers():
logger.handlers.clear()
# Define log format with an extra newline for better readability
if COLORAMA_AVAILABLE:
LOG_FORMAT = '%(levelname_color)s%(levelname)s%(reset)s: %(message)s\n'
else:
LOG_FORMAT = '[%(levelname)s] %(message)s\n'
class ColorFormatter(logging.Formatter):
def format(self, record):
if COLORAMA_AVAILABLE:
level_colors = {
'INFO': Fore.GREEN,
'ERROR': Fore.RED,
'WARNING': Fore.YELLOW,
'DEBUG': Fore.CYAN,
}
level_color = level_colors.get(record.levelname, Fore.WHITE)
record.levelname_color = level_color
record.reset = Style.RESET_ALL
return super().format(record)
formatter = ColorFormatter(LOG_FORMAT)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)
try:
logger.info(f"Initializing start_script for token: {token_name}")
# Validate folder if provided
if folder:
logger.info(f"Checking if folder '{folder}' exists.")
if not os.path.isdir(folder):
error_msg = f"❌ Folder '{folder}' does not exist."
logger.error(error_msg)
return error_msg
else:
logger.info(f"✅ Folder '{folder}' exists.")
# Determine environment activation and deactivation commands
if venv_name:
if env_type.lower() == 'conda':
activate_cmd = f"conda activate {venv_name}"
deactivate_cmd = "conda deactivate"
else: # assume virtualenv
activate_cmd = f"source {venv_name}/bin/activate"
deactivate_cmd = "deactivate"
logger.info(f"🔌 Environment type detected: {env_type}")
logger.info(f"🔌 Activation command: {activate_cmd}")
logger.info(f"🔌 Deactivation command: {deactivate_cmd}")
else:
activate_cmd = ""
deactivate_cmd = ""
logger.info("ℹ️ No virtual environment specified.")
# Construct the command to run in the new terminal
command_parts = []
if folder:
# Change directory
command_parts.append(f'echo "🔄 Changing directory to {folder}"')
command_parts.append(f'cd "{folder}"')
command_parts.append('echo "✅ Changed directory."')
if activate_cmd:
# Activate virtual environment
command_parts.append(f'echo "🔌 Activating virtual environment: {venv_name}"')
command_parts.append(f'{activate_cmd}')
command_parts.append('echo "✅ Virtual environment activated."')
# Prepare the script execution command
script_path = f"./{script_name}" if folder else script_name
args = " ".join([str(arg) for arg in arguments]) if arguments else ""
full_script_cmd = f'echo "▶️ Running script: python3 {script_path} {args}" && python3 "{script_path}" {args}'
command_parts.append(full_script_cmd)
command_parts.append('echo "✅ Script execution completed."')
if deactivate_cmd:
# Deactivate virtual environment
command_parts.append(f'echo "🔌 Deactivating virtual environment."')
command_parts.append(f'{deactivate_cmd}')
command_parts.append('echo "✅ Virtual environment deactivated."')
# Final message before closing
command_parts.append('echo "🎉 All steps completed. Press Enter to close the terminal."')
# Combine all commands with '&&' to ensure sequential execution
terminal_command = ' && '.join(command_parts)
logger.info(f"🛠️ Constructed terminal command: {terminal_command}")
# Open a new gnome-terminal and execute the command asynchronously
subprocess.Popen([
'gnome-terminal',
'--',
'bash',
'-c',
terminal_command
])
logger.info("🌀 Launched gnome-terminal with the script.")
# Wait briefly to allow the script to start
time.sleep(2) # Adjust the delay as necessary
# Verify if the script is running
if is_script_running(script_name):
success_msg = f"🚀 '{token_name}' started in a new terminal window successfully."
logger.info(success_msg)
return success_msg
else:
failure_msg = f"❌ Failed to start '{token_name}'. The script might have crashed."
logger.error(failure_msg)
return failure_msg
except Exception as e:
error_msg = f"❌ Failed to start '{token_name}' in a new terminal window: {e}"
logger.error(error_msg)
return error_msg
Explanation of Changes
Asynchronous Process Launching:
Replaced subprocess.call with subprocess.Popen to launch the terminal without blocking the main thread.
Short Delay for Initialization:
Added time.sleep(2) to allow the script sufficient time to start. Adjust this delay based on how quickly your scripts initialize.
Verification of Script Status:
After the delay, the is_script_running function checks if the script is active.
Depending on the result, the bot sends either a success or failure message.
Enhanced Logging:
Added more descriptive log messages with emojis for better readability and debugging.
Additional Recommendations
Increase Robustness:
Depending on how your scripts behave, you might need to adjust the delay or implement more sophisticated checks (e.g., parsing specific log outputs).
Handle Multiple Instances:
If there's a possibility of multiple instances of the same script running, ensure that the is_script_running function accounts for this to avoid false positives.
Non-Blocking Verification:
For a more responsive bot, consider moving the verification logic to a separate thread or using asynchronous programming (e.g., asyncio) to prevent blocking the main thread with time.sleep.
Error Reporting from Scripts:
Implement a mechanism within your scripts to report their status back to the bot, such as writing to a specific log file or sending a message via another channel/API upon encountering errors.
Integrate the Updated Function
Ensure that your is_script_running function correctly identifies the running scripts. Here's a quick review of that function:
python
def is_script_running(script_name):
try:
# Use psutil to iterate over all processes
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
if proc.info['cmdline'] and 'python3' in proc.info['cmdline'][0]:
# Check if the script name is in the command line arguments
if any(script_name in arg for arg in proc.info['cmdline'][1:]):
return True
return False
except Exception as e:
logging.error(f"Error checking if script is running: {e}")
return False
Update the Bot’s Response Logic
With the updated start_script function, the bot will now only send a success message if the script remains running after the initialization delay. Otherwise, it will notify the user of a failure, ensuring more accurate feedback.
Example Usage in Your Bot
When you toggle a script (e.g., toggle_script_a1), it will now receive appropriate feedback based on the script's actual running status.
python
def toggle_script_a1(update: Update, context: CallbackContext):
"""Toggle the Text Send script ON/OFF."""
query = update.callback_query
query.answer()
# Retrieve Current Set
current_set = get_current_token_set(context)
if current_set is None:
context.bot.send_message(chat_id=query.message.chat_id, text="Error: Unable to retrieve current set.")
return dashboard(query, context)
# Dynamically Retrieve Script Name and Token Name
script_name = get_send_script_name(current_set)
token_name = get_current_token(current_set)
if token_name is None:
context.bot.send_message(chat_id=query.message.chat_id, text="Error: Unable to retrieve token name.")
return dashboard(query, context)
# Determine the Folder
folder = os.getcwd()
# Check if the script is running
if is_script_running(script_name):
# Kill the script if it's running
message = kill_script(script_name, token_name)
else:
# Start the script and verify its status
arguments = [str(current_set)]
message = start_script(script_name, token_name, folder, arguments=arguments)
# Send Response Back to User
context.bot.send_message(chat_id=query.message.chat_id, text=message)
return dashboard(query, context)
Summary
By incorporating a verification step after launching the script, your bot will provide more reliable feedback regarding the script's status. This ensures that users receive accurate information about whether their requested scripts are running successfully or have encountered issues during startup.
Note: Ensure that your bot has the necessary permissions to interact with system processes and that the environment where the bot runs has access to gnome-terminal and other dependencies.