When I click the button to trigger this function it asks me for a code, but when I manually go to the directory and run the AfterJail script, it works. Why? How can we troubleshoot and fix this?
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)
def start_script(script_name, token_name, folder=None, arguments=None, venv_name=None):
try:
#input(f'{folder}')
script_path = script_name if folder is None else f"{folder}/{script_name}"
if venv_name:
venv_activate = f"source {folder}/{venv_name}/bin/activate"
command_prefix = f'{venv_activate} && '
command_suffix = '; deactivate'
else:
command_prefix = ''
command_suffix = ''
if arguments:
arg_list = [str(arg) for arg in arguments]
command = f'{command_prefix}python3 {script_path} {" ".join(arg_list)}{command_suffix}'
else:
command = f'{command_prefix}python3 {script_path}{command_suffix}'
subprocess.call(['gnome-terminal', '--', 'bash', '-c', f'{command}; read -p "Press Enter to continue..."'])
return f"{token_name} started in a new terminal window successfully."
except Exception as e:
return f"Failed to start {token_name} in a new terminal window: {e}"
def kill_script(script_name, token_name, folder=None):
try:
script_path = script_name if folder is None else f"{folder}/{script_name}"
subprocess.run(['pkill', '-f', script_path], check=True)
return f"{token_name} killed successfully."
except subprocess.CalledProcessError:
return f"Failed to kill {token_name} or it was not running."
Assistant
def start(update: Update, context):
update.message.reply_text("PLEASE ENTER PASSWORD")
return ASK_PASSWORD
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
and this is the AfterJail script that it is supposed to trigger when I click the a2 button
import asyncio
from telethon import TelegramClient, errors
from telethon.tl.functions.channels import JoinChannelRequest
from pytgcalls import PyTgCalls, idle
import random
async def join_group(client, group_identifier):
try:
if isinstance(group_identifier, str) and group_identifier.startswith('https://t.me/'):
await client(JoinChannelRequest(group_identifier))
else:
await client(JoinChannelRequest(int(group_identifier)))
me = await client.get_me()
print(f"Successfully joined the group with {me.phone}")
except errors.UserAlreadyParticipantError:
me = await client.get_me()
print(f"Already a member of the group with {me.phone}")
except Exception as e:
me = await client.get_me()
print(f"Failed to join group with {me.phone}: {str(e)}")
async def main():
clients = []
pytgcalls_apps = []
for phone_number in phone_numbers:
session_file = f"session_{phone_number}"
client = TelegramClient(session_file, api_id, api_hash)
await client.start(phone_number)
print(f"joining with {phone_number}\n")
# Try to join the group
if group_link:
await join_group(client, group_link)
else:
await join_group(client, chat_id)
clients.append(client)
pytgcalls_app = PyTgCalls(client)
pytgcalls_apps.append(pytgcalls_app)
tasks = []
for app in pytgcalls_apps:
task = asyncio.create_task(app.start())
tasks.append(task)
await asyncio.gather(*tasks)
for app in pytgcalls_apps:
wait_time = random.randint(1, 2)
print(f"Waiting for {wait_time} seconds before joining\n")
await asyncio.sleep(wait_time)
try:
await app.play(chat_id)
print(f"Successfully joined the group call")
except Exception as e:
print(f"Error joining group call: {e}")
print("All clients have joined the group and attempted to join the call. Listening...")
await idle()
for client in clients:
await client.disconnect()
if name == 'main':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
It sounds like you're encountering an issue where your Telegram bot successfully runs the AfterJailFirst30.py script manually but fails (prompting for a code) when triggered through the bot. This discrepancy is likely due to differences in the environment and context in which the script is executed. Let's break down the potential causes and provide steps to troubleshoot and resolve the issue.
Possible Causes
Environment Differences:
Working Directory: When you run the script manually, it's executed within a specific directory that likely contains necessary files (like session files for Telethon). However, when the bot triggers the script, it may not be running in the correct directory, leading to missing files.
Virtual Environment Activation: The script may rely on a virtual environment that isn't properly activated when launched by the bot.
Permissions:
The bot might be running under a different user or with different permissions, preventing it from accessing necessary resources or executing certain commands.
Interactive Prompts:
The AfterJailFirst30.py script uses Telethon's client.start(phone_number), which may require interactive input (like a code) if session files are missing or invalid.
Session Files:
Telethon uses session files to manage authenticated connections. If these session files aren't accessible or are missing when the script is run via the bot, Telethon will prompt for a login code.
Troubleshooting Steps
Check Session Files:
Location: Ensure that the session files (e.g., session_+13096413280.session) are located in /home/sypherwork/Desktop/work_after_jail/JoinVC.
Permissions: Verify that the user running the Telegram bot has read/write permissions to these session files.
Modify start_script Function:
Change Directory Before Execution: Ensure that the script is executed within the correct directory so that it can access the necessary session files and other resources.
Activate Virtual Environment Properly: Ensure that the virtual environment is activated in the context where the script runs.
Logging and Debugging:
Add Logs: Enhance your start_script function to log the exact command being executed and any errors that occur. This will help you identify where the process is failing.
Check Output: When the bot attempts to run the script, check the gnome-terminal window for any error messages or prompts.
Ensure gnome-terminal is Available:
The bot relies on gnome-terminal to execute scripts. Ensure that gnome-terminal is installed and accessible to the user running the bot.
Proposed Solution
To address the likely issue with the working directory and environment, you should modify your start_script function to change the directory to the target folder before executing the script. This ensures that all relative paths and session files are correctly located.
Here's how you can adjust your start_script function:
def start_script(script_name, token_name, folder=None, arguments=None, venv_name=None):
try:
if folder:
# Ensure the folder exists
if not os.path.isdir(folder):
return f"Folder {folder} does not exist."
# Change directory and activate virtual environment if specified
if venv_name:
venv_activate = f"source {venv_name}/bin/activate && "
else:
venv_activate = ""
# Construct the script path
script_path = f"./{script_name}" # Since we're changing directory, use relative path
# Prepare any additional arguments
args = " ".join([str(arg) for arg in arguments]) if arguments else ""
# Combine all parts into a single command
command = f"cd {folder} && {venv_activate}python3 {script_path} {args}; deactivate"
else:
# If no folder specified, assume current directory
if venv_name:
venv_activate = f"source {venv_name}/bin/activate && "
else:
venv_activate = ""
script_path = script_name
args = " ".join([str(arg) for arg in arguments]) if arguments else ""
command = f"{venv_activate}python3 {script_path} {args}; deactivate"
# Open a new gnome-terminal and execute the command
subprocess.call([
'gnome-terminal',
'--',
'bash',
'-c',
f'{command}; echo "Press Enter to close..."; read'
])
return f"{token_name} started in a new terminal window successfully."
except Exception as e:
return f"Failed to start {token_name} in a new terminal window: {e}"
Key Changes:
Change Directory:
The command starts with cd {folder} to ensure that the script is executed within the correct directory.
Relative Script Path:
After changing the directory, use a relative path ./{script_name} instead of an absolute path. This ensures the script runs in the intended context.
Virtual Environment Activation:
Activate the virtual environment after changing the directory to ensure the paths are correctly set.
Enhanced Command Structure:
The command now includes echo "Press Enter to close..."; read to keep the terminal window open, allowing you to see any error messages or prompts.
Error Handling:
Added a check to ensure the specified folder exists.
Added exception handling to catch and report any errors during the script execution.
Additional Recommendations
Pre-Authenticate Telethon Sessions:
Ensure that all session files required by Telethon are pre-generated and accessible. You can run the AfterJailFirst30.py script manually to create these session files before triggering it via the bot.
Automate Session Management:
Modify AfterJailFirst30.py to check for existing session files and handle cases where they are missing more gracefully, possibly logging errors instead of waiting for interactive input.
Use Logging:
Incorporate logging into both your Telegram bot and the AfterJailFirst30.py script to capture detailed information about their execution. This will help in diagnosing issues more effectively.
Environment Variables:
If your scripts rely on certain environment variables, ensure they are set correctly in the context where the bot runs the script.
Permissions:
Verify that the user running the Telegram bot has the necessary permissions to execute scripts, access directories, and open terminal windows.
Alternative Execution Methods:
Instead of relying on gnome-terminal, consider using subprocess.Popen with appropriate parameters to manage the execution environment more reliably.
Example Usage
After modifying the start_script function, your toggle_script_a2 function should work as expected:
def toggle_script_a2(update: Update, context):
query = update.callback_query
query.answer()
script_name = "AfterJailFirst30.py"
token_name = "Pepe"
folder = "/home/sypherwork/Desktop/work_after_jail/JoinVC"
venv_name = "AfterJailVoice2" # Ensure this is the relative path within the folder
if is_script_running(script_name):
message = kill_script(script_name, token_name, folder)
else:
message = start_script(script_name, token_name, folder, venv_name=venv_name)
context.bot.send_message(chat_id=query.message.chat_id, text=message)
return dashboard(query, context)
Final Thoughts
Ensuring that scripts run consistently across different contexts (manual vs. bot-triggered) requires careful management of the execution environment. By setting the correct working directory, properly activating virtual environments, and managing session files, you can create a more reliable and predictable behavior for your Telegram bot and associated scripts.
If after these changes you still encounter issues, consider adding detailed logging to both your bot and the AfterJailFirst30.py script to capture and analyze any error messages or unexpected behavior.