def kill_script(script_name, token_name, folder=None):
try:
# Include 'python3' to be more specific
subprocess.run(['pkill', '-f', f'python3 .*{script_name}'], check=True)
return f"{script_name} for token:{token_name} killed successfully."
except subprocess.CalledProcessError:
return f"Failed to kill {script_name} for token:{token_name}, or it was not running."
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:
if folder:
# Ensure the folder exists
if not os.path.isdir(folder):
return f"Folder {folder} does not exist."
code
Assistant
# 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}"
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
BUT IT ALSO GIVES ME THIS ERROR IN THE CONSOLE, WHY DOES IT GIVE ME THIS ERROR?
Traceback (most recent call last):
File "/home/sypherwork/miniconda3/lib/python3.10/site-packages/telegram/ext/dispatcher.py", line 555, in process_update
handler.handle_update(update, self, check, context)
File "/home/sypherwork/miniconda3/lib/python3.10/site-packages/telegram/ext/conversationhandler.py", line 626, in handle_update
new_state = handler.handle_update(update, dispatcher, check_result, context)
File "/home/sypherwork/miniconda3/lib/python3.10/site-packages/telegram/ext/handler.py", line 198, in handle_update
return self.callback(update, context)
File "/home/sypherwork/Desktop/work_after_jail/JUNE_UPGRADE/hYPEbOIS3.py", line 154, in toggle_script_a1
return dashboard(query, context)
File "/home/sypherwork/Desktop/work_after_jail/JUNE_UPGRADE/hYPEbOIS3.py", line 198, in dashboard
if update.callback_query:
AttributeError: 'CallbackQuery' object has no attribute 'callback_query'
No error handlers are registered, logging exception.
Traceback (most recent call last):
File "/home/sypherwork/miniconda3/lib/python3.10/site-packages/telegram/ext/dispatcher.py", line 555, in process_update
handler.handle_update(update, self, check, context)
File "/home/sypherwork/miniconda3/lib/python3.10/site-packages/telegram/ext/conversationhandler.py", line 626, in handle_update
new_state = handler.handle_update(update, dispatcher, check_result, context)
File "/home/sypherwork/miniconda3/lib/python3.10/site-packages/telegram/ext/handler.py", line 198, in handle_update
return self.callback(update, context)
File "/home/sypherwork/Desktop/work_after_jail/JUNE_UPGRADE/hYPEbOIS3.py", line 154, in toggle_script_a1
return dashboard(query, context)
File "/home/sypherwork/Desktop/work_after_jail/JUNE_UPGRADE/hYPEbOIS3.py", line 198, in dashboard
if update.callback_query:
AttributeError: 'CallbackQuery' object has no attribute 'callback_query'
The error you're encountering arises because the dashboard function is being called with a CallbackQuery object instead of the expected Update object. Let me break down the issue and provide a detailed solution to resolve it.
Understanding the Error
Error Message:
code
AttributeError: 'CallbackQuery' object has no attribute 'callback_query'
Cause:
In your handler functions (e.g., toggle_script_a1, toggle_script_a2), you're passing the query (which is a CallbackQuery object) to the dashboard function.
The dashboard function expects an Update object, not a CallbackQuery object.
Inside the dashboard function, it attempts to access update.callback_query, but since update is actually a CallbackQuery, this attribute doesn't exist, leading to the AttributeError.
Solution
Step 1: Pass the Correct update Object to dashboard
In your handler functions, ensure you're passing the entire update object to the dashboard function, not just the query. Here's how you can modify your handler functions:
While not directly related to your current error, it's good practice to add error handlers to your bot. This ensures that unexpected errors are gracefully handled and logged.
python
def error_handler(update: object, context: CallbackContext) -> None:
"""Log the error and send a message to the user."""
logger.error(msg="Exception while handling an update:", exc_info=context.error)
if isinstance(update, Update) and update.effective_user:
context.bot.send_message(
chat_id=update.effective_user.id,
text="An unexpected error occurred. Please try again later."
)
# In your main function, add the error handler:
updater.dispatcher.add_error_handler(error_handler)
Security:
Do not share your bot token publicly. In your script, the token is visible:
Immediately revoke this token and generate a new one via BotFather.
Code Organization:
Consider organizing your handlers more systematically. For instance, grouping similar handlers or using separate modules for different functionalities can improve readability and maintainability.
Logging:
Implement logging to monitor the bot's behavior and debug issues more effectively.
Here's how your corrected toggle_script_a1 handler should look:
python
def toggle_script_a1(update: Update, context: CallbackContext):
"""Toggle the Text Send script ON/OFF."""
query = update.callback_query
query.answer()
# 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(update, context) # Pass 'update', not 'query'
# 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(update, context) # Pass 'update', not 'query'
# Step 3: Determine the Folder
folder = "/home/sypherwork/Desktop/work_after_jail/JUNE_UPGRADE"
# 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(update, context) # Pass 'update', not 'query'
Conclusion
By ensuring that you're consistently passing the correct Update object to functions that expect it, you'll prevent such AttributeErrors. Additionally, adopting best practices like secure token management, logging, and organized code structure will enhance the reliability and maintainability of your Telegram bot.
If you follow these corrections, the error should be resolved, and your bot should function as expected without triggering the AttributeError.
Important Reminder: Always keep your bot tokens secure. If you've inadvertently shared your bot token (as in your current script), make sure to revoke it immediately through BotFather and generate a new one to prevent unauthorized access to your bot.
Feel free to reach out if you encounter further issues or have additional questions!
Ensure you're using a compatible version of the python-telegram-bot library. Some methods and functionalities might differ between versions, leading to unexpected behaviors.