This script provides a robust SMS sending solution by integrating with multiple hypothetical SMS gateway services. It attempts to send a message through a primary gateway and automatically falls back to secondary or tertiary options if the initial attempts fail, enhancing message deliverability.
import random
import time
class SmsGateway:
"""
Represents a single SMS service provider gateway.
This class simulates sending SMS and can be extended to integrate with
actual SMS APIs (e.g., Kavenegar, Melipayamak, Twilio, Nexmo, etc.).
"""
def __init__(self, name, api_key='dummy_key', endpoint='https://api.example.com/sms'):
"""
Initializes an SMS gateway with its configuration.
Args:
name (str): A descriptive name for the SMS provider (e.g., 'Provider A', 'Kavenegar').
api_key (str): The API key for this specific provider. (Placeholder for real integration).
endpoint (str): The API endpoint URL for sending messages. (Placeholder for real integration).
"""
self.name = name
self.api_key = api_key
self.endpoint = endpoint
print(f'[{self.name}] Gateway initialized.')
def send_sms(self, recipient_number, message):
"""
Simulates sending an SMS message using this gateway.
In a real application, this method would make an HTTP request
to the actual SMS provider's API using its specific parameters.
Args:
recipient_number (str): The phone number to send the SMS to.
message (str): The text content of the SMS.
Returns:
bool: True if the SMS was 'sent' successfully, False otherwise.
"""
print(f'[{self.name}] Attempting to send SMS to {recipient_number}: "{message}"...')
time.sleep(1) # Simulate network latency for API call
# --- REAL API INTEGRATION GOES HERE ---
# You would replace this simulation with actual API calls to the SMS provider.
# Example using the 'requests' library (install with: pip install requests):
#
# import requests
# try:
# payload = {
# 'api_key': self.api_key,
# 'to': recipient_number,
# 'text': message,
# # Add other parameters required by the specific provider
# }
# headers = {
# 'Content-Type': 'application/json' # or 'application/x-www-form-urlencoded'
# }
# response = requests.post(self.endpoint, json=payload, headers=headers, timeout=10)
#
# if response.status_code == 200 and response.json().get('status') == 'success':
# print(f'[{self.name}] SMS sent successfully via {self.name}.')
# return True
# else:
# print(f'[{self.name}] Failed to send SMS via {self.name}. Status: {response.status_code}, Response: {response.text}')
# return False
# except requests.exceptions.RequestException as e:
# print(f'[{self.name}] Network error or API call failed: {e}')
# return False
# ----------------------------------------
# For demonstration, we simulate success/failure randomly to test fallback logic.
# Success probability can be adjusted per gateway to simulate reliability differences.
success_chance = 0.7 if self.name == 'SMS Provider A (Kavenegar Mock)' else \
(0.8 if self.name == 'SMS Provider B (Melipayamak Mock)' else 0.9)
if random.random() < success_chance:
print(f'[{self.name}] SMS sent successfully (simulated).')
return True
else:
print(f'[{self.name}] Failed to send SMS (simulated failure).')
return False
def send_sms_with_fallback(recipient_number, message, gateways):
"""
Attempts to send an SMS using a list of provided gateways, trying each in order
and falling back to the next one if the current gateway fails.
This implements a 'multi-hub' strategy for robust SMS delivery.
Args:
recipient_number (str): The phone number to send the SMS to.
message (str): The text content of the SMS.
gateways (list[SmsGateway]): A list of SmsGateway instances to try in order of priority.
Returns:
tuple[bool, str | None]: A tuple where the first element is True if the SMS was
successfully sent by any gateway, False otherwise. The
second element is the name of the gateway that succeeded,
or None if all attempts failed.
"""
print(f'\n--- Attempting to send message to {recipient_number} with fallback strategy ---')
for i, gateway in enumerate(gateways):
print(f'Trying gateway {i + 1}/{len(gateways)}: {gateway.name}')
if gateway.send_sms(recipient_number, message):
print(f'Message successfully sent by {gateway.name}.')
return True, gateway.name
else:
print(f'Gateway {gateway.name} failed. Attempting next gateway...')
print('All configured SMS gateways failed to send the message.')
return False, None
# --- Main execution part of the script ---
if __name__ == '__main__':
# 1. Define your SMS gateways
# In a real application, you would configure these with actual API keys
# and endpoints obtained from your chosen SMS providers.
# Replace 'YOUR_API_KEY' and example endpoints with actual provider details.
provider_a = SmsGateway(
name='SMS Provider A (Kavenegar Mock)',
api_key='YOUR_KAVENEGAR_API_KEY',
endpoint='https://api.kavenegar.com/v1/{API_KEY}/sms/send.json' # Example Kavenegar endpoint
)
provider_b = SmsGateway(
name='SMS Provider B (Melipayamak Mock)',
api_key='YOUR_MELIPAYAMAK_API_KEY',
endpoint='https://rest.melipayamak.com/api/send/simple' # Example Melipayamak endpoint
)
provider_c = SmsGateway(
name='SMS Provider C (Sms.ir Mock)',
api_key='YOUR_SMSIR_API_KEY',
endpoint='https://ws.sms.ir/api/SMS/Send' # Example Sms.ir endpoint
)
# Group your gateways into a list (this forms your 'hubs' for sending).
# The order in this list determines the priority for sending.
sms_hubs = [provider_a, provider_b, provider_c]
# For larger systems, these configurations could be loaded from a config file or database.
# 2. Specify the recipient and message content
target_number = '09123456789' # Replace with an actual recipient phone number
sms_content = 'Hello from the Python multi-gateway SMS sender! This is a test.'
# 3. Send the SMS using the defined fallback strategy
success, sent_by_gateway = send_sms_with_fallback(target_number, sms_content, sms_hubs)
if success:
print(f'\nFinal Result: SMS successfully delivered via {sent_by_gateway}.')
else:
print('\nFinal Result: SMS delivery failed through all available gateways.')
print('\n--- Demonstrating another send that might require fallback ---')
another_target = '09301234567'
another_content = 'Important Alert: System status requires immediate attention!'
success_2, sent_by_gateway_2 = send_sms_with_fallback(another_target, another_content, sms_hubs)
if success_2:
print(f'\nFinal Result: Second SMS successfully delivered via {sent_by_gateway_2}.')
else:
print('\nFinal Result: Second SMS delivery failed through all available gateways.')