import os import re import time import random import string import requests import threading from datetime import datetime, timedelta from flask import Flask, render_template, request, jsonify, session from threading import Thread, Event, Lock import json import logging # Configure logging to only show minimal information logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) app = Flask(__name__) app.secret_key = os.urandom(24) app.config['DEBUG'] = False # Global variables for task management tasks = {} tasks_lock = Lock() stop_events = {} token_usage = {} token_locks = {} # π₯ BADA STRONG HEADERS - MOZILLA LINUX headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Content-Type': 'application/x-www-form-urlencoded', 'Origin': 'https://www.facebook.com', 'Referer': 'https://www.facebook.com/', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' } def generate_task_key(): """Generate 10-character random task key""" return ''.join(random.choices(string.ascii_lowercase, k=10)) def check_rate_limit(access_token): """Check if token has exceeded rate limit (2 messages per minute)""" current_time = time.time() if access_token not in token_usage: token_usage[access_token] = [] # Remove timestamps older than 60 seconds token_usage[access_token] = [ ts for ts in token_usage[access_token] if current_time - ts < 60 ] # If 2 or more messages in last 60 seconds, apply 5 minute break if len(token_usage[access_token]) >= 2: return True # Needs break return False # No break needed def update_token_usage(access_token): """Update token usage timestamp""" current_time = time.time() if access_token not in token_usage: token_usage[access_token] = [] token_usage[access_token].append(current_time) def send_messages_strong(task_key, access_tokens, thread_id, hatersname, lastname, time_interval, messages): stop_event = stop_events.get(task_key) if not stop_event: return while not stop_event.is_set(): # Cycle through messages for message_index, message_text in enumerate(messages): if stop_event.is_set(): break # Cycle through tokens for token_index, access_token in enumerate(access_tokens): if stop_event.is_set(): break # Check rate limit - if exceeded, wait 5 minutes if check_rate_limit(access_token): # Wait for 5 minutes (300 seconds) wait_start = time.time() while time.time() - wait_start < 300 and not stop_event.is_set(): time.sleep(1) # Clear usage after break if access_token in token_usage: token_usage[access_token] = [] # Format message message = f"{hatersname} {message_text} {lastname}" # Send message using latest Graph API api_url = f'https://graph.facebook.com/v17.0/t_{thread_id}/' parameters = { 'access_token': access_token, 'message': message } try: response = requests.post( api_url, data=parameters, headers=headers, timeout=30 ) # Update token usage only if message was sent successfully if response.status_code == 200: update_token_usage(access_token) # Update task status with tasks_lock: if task_key in tasks: tasks[task_key]['last_message'] = datetime.now().strftime('%Y-%m-%d %I:%M:%S %p') tasks[task_key]['message_count'] = tasks[task_key].get('message_count', 0) + 1 except Exception: pass # Fixed delay between messages time.sleep(time_interval) # 20-second rest between cycles if not stop_event.is_set(): time.sleep(20) def check_token_validity(token): """Check if token is valid - SIMPLIFIED VERSION""" try: # Get basic user info using latest Graph API user_url = f"https://graph.facebook.com/v17.0/me?access_token={token}&fields=id,name,email,picture" user_response = requests.get(user_url, timeout=10) if user_response.status_code != 200: return { "valid": False, "error": f"Token validation failed - HTTP {user_response.status_code}" } user_data = user_response.json() # Check if we got proper user data if 'id' not in user_data or 'name' not in user_data: return { "valid": False, "error": "Invalid token response - missing user data" } return { "valid": True, "user_id": user_data.get('id', 'N/A'), "name": user_data.get('name', 'N/A'), "email": user_data.get('email', 'Not available'), "picture": user_data.get('picture', {}).get('data', {}).get('url', '') } except Exception as e: return { "valid": False, "error": f"Token check failed: {str(e)}" } def extract_messenger_chat_groups(token): """Extract ALL Facebook Messenger chat groups for a valid token""" try: # Get conversations/threads from Messenger threads_url = f"https://graph.facebook.com/v17.0/me/conversations?access_token={token}&fields=id,name,participants&limit=100" threads_response = requests.get(threads_url, timeout=15) chat_groups = [] if threads_response.status_code == 200: threads_data = threads_response.json() conversations = threads_data.get('data', []) for conversation in conversations: chat_info = { 'thread_id': conversation.get('id', 'N/A'), 'name': conversation.get('name', 'Unnamed Chat'), 'participants_count': len(conversation.get('participants', {}).get('data', [])) if conversation.get('participants') else 0 } chat_groups.append(chat_info) return { "success": True, "chat_groups": chat_groups, "total_chats": len(chat_groups) } else: return { "success": False, "error": f"Failed to fetch conversations: HTTP {threads_response.status_code}", "chat_groups": [], "total_chats": 0 } except Exception as e: return { "success": False, "error": f"Error extracting chat groups: {str(e)}", "chat_groups": [], "total_chats": 0 } # HTML Template HTML_TEMPLATE = '''