import requests import time import json import os from datetime import datetime # Replace this with your actual API key TELNYX_API_KEY = "KEY0198614F22EB03F1EA32D2AA316730A1_p8o1tpLIuCYXifiDEVfaGH" url = "https://api.telnyx.com/v2/texml/calls/2751729651297551626" headers = { "Authorization": f"Bearer {TELNYX_API_KEY}", "Content-Type": "application/json" } def get_call_status(call_control_id): # Define the endpoint URL url = f"https://api.telnyx.com/v2/calls/{call_control_id}" # Set up the headers with your API key headers = { "Authorization": f"Bearer {TELNYX_API_KEY}" } # Make the GET request to retrieve the call status response = requests.get(url, headers=headers) # Check if the request was successful if response.status_code == 200: # Parse the response JSON call_details = response.json() is_alive = call_details['data']['is_alive'] if not is_alive: # Check the call status using cause codes cause_code = call_details['data'].get('cause_code') if cause_code == 16: print("The call was completed normally.") elif cause_code == 602: print("The call went unanswered.") elif cause_code == 17: print("The called party was busy.") elif cause_code == 1: print("The number dialed is invalid.") elif cause_code == 21: print("The call was rejected.") else: print(f"Call ended with cause code: {cause_code}") return cause_code else: cause_code = 1 return cause_code else: print(f"Failed to retrieve call status: {response.status_code} - {response.text}") return 0 phone_numbers = [ "+2348034574529", "+263777496411", "+447394709273", "+22544790879", "+250726612041", "+22363498904", "+233244993400", "+2206668534", "+2206743505", "+211928633373", "+2348035999486", "+244923792859", "+23592010902", "+264812391005", "+251930433333", "+265885575021", "+260974295373", "+971553490359", "+2306276248", "+237651908224", "+201002460790", "+23233041965", "+22799130303", "+233533110003", "+255713214414", "+2348134664267", "+2349030653330", "+2348034123778", "+22797044971", "+254708151526", "+224628339215", "+261345573633", "+252616673638", "+25761032313", "+2348162049611", "+218925600708", "+2524413824", "+2349094855642", "+224620993406", "+254711707194", "+251911420926", "+255713322976", "+254725953485", "+251911630362", "+919655185526", "+252907630277", "+252634517725", "+254737726202", "+252907950463", "+782009264", "+258863446684", "+260979927475", "+201111415111", "+263772640982", "+244931019092", "+2348038408889", "+243821973505", "+243898801067", "+265986576883", "+231776846097", "+22672633341", "+25767802749", "+26772338899", "+260974918207", "+254733596485", "+243898801067", "+2348130664989", "+251936993065", "+27744730746", "+23276940005" ] # phone_numbers = [ # "+918149141050" # ] # Create a list to store all call responses all_responses = [] # Create logs directory if it doesn't exist logs_dir = "logs" if not os.path.exists(logs_dir): os.makedirs(logs_dir) print(f"Created logs directory: {logs_dir}") # Use daily filename based on current date current_date = datetime.now().strftime("%Y-%m-%d") json_filename = os.path.join(logs_dir, f"telnyx_calls_{current_date}.json") # Load existing data if file exists for today if os.path.exists(json_filename): try: with open(json_filename, 'r') as f: existing_data = json.load(f) all_responses = existing_data.get('calls', []) print(f"Loaded {len(all_responses)} existing call records from {json_filename}") except (json.JSONDecodeError, KeyError): print(f"Error reading existing file {json_filename}, starting fresh") all_responses = [] else: print(f"Creating new daily log file: {json_filename}") all_responses = [] total_calls, successful_calls = 0,0 for single_number in phone_numbers: print(f"Calling {single_number}") data = { "From": "+16692056010", "To": single_number } try: response = requests.post(url, headers=headers, json=data) response_json = response.json() # Create a record for this call print(f"Status Code: {response.status_code}") call_sid = response_json.get("call_sid", None) call_status = "NA" if call_sid: call_status = get_call_status(call_sid) #if call is still ongoing while call_status == 1: time.sleep(120) call_status = get_call_status(call_sid) # if call_status == 16: successful_calls = successful_calls +1 else: call_sid = "NA" total_calls = total_calls+1 call_record = { "timestamp": datetime.now().isoformat(), "phone_number": single_number, "request_data": data, "status_code": response.status_code, "response": response.json() if response.status_code == 200 else response.text, "success": response.status_code == 200, "call_sid":call_sid, "call_status":call_status } print(f"Response: {call_record['response']}") # Add to our collection all_responses.append(call_record) # Save to JSON file after each call (appending to existing data) with open(json_filename, 'w') as f: json.dump({ "date": current_date, "total_calls": len(all_responses), "last_updated": datetime.now().isoformat(), "calls": all_responses }, f, indent=2) print(f"JSON decode error logged to {json_filename} (Total calls today: {len(all_responses)})") print(f"Response appended to {json_filename} (Total calls: {len(all_responses)})") print(total_calls, successful_calls) if successful_calls/total_calls < 0.6: time.sleep(1200) else: time.sleep(600) except requests.exceptions.RequestException as e: print(f"Error making request to {single_number}: {e}") total_calls = total_calls+1 # Still save error information error_record = { "timestamp": datetime.now().isoformat(), "phone_number": single_number, "request_data": data, "error": str(e), "success": False } all_responses.append(error_record) # Update daily JSON file with error info with open(json_filename, 'w') as f: json.dump({ "date": current_date, "total_calls": len(all_responses), "last_updated": datetime.now().isoformat(), "calls": all_responses }, f, indent=2) print(f"Error logged to {json_filename} (Total calls today: {len(all_responses)})") time.sleep(1200) except json.JSONDecodeError: print(f"Error decoding JSON response for {single_number}") total_calls = total_calls+1 # Save raw response if JSON decode fails raw_record = { "timestamp": datetime.now().isoformat(), "phone_number": single_number, "request_data": data, "status_code": response.status_code, "raw_response": response.text, "json_decode_error": True, "success": False } all_responses.append(raw_record) with open(json_filename, 'w') as f: json.dump({ "total_calls": len(all_responses), "last_updated": datetime.now().isoformat(), "calls": all_responses }, f, indent=2) time.sleep(1200) print("-" * 50) # time.sleep(480) # Wait 8 minutes between calls print(f"\nAll call responses have been saved to: {json_filename}") print(f"Total calls processed: {len(all_responses)}") # Print summary successful_calls = sum(1 for call in all_responses if call.get('success', False)) failed_calls = len(all_responses) - successful_calls print(f"Successful calls: {successful_calls}") print(f"Failed calls: {failed_calls}")