### Install Dependencies with Pip Source: https://github.com/solapi/solapi-python/blob/main/tests/README.md Installs the pytest framework, a necessary dependency for running the SOLAPI Python SDK tests. Ensure you have Python 3.9 or higher installed. ```bash pip install pytest ``` -------------------------------- ### Send Messages with Custom Metadata using Solapi Python SDK Source: https://context7.com/solapi/solapi-python/llms.txt This code example shows how to send messages using the Solapi Python SDK and attach custom fields for tracking and categorization. It initializes the `SolapiMessageService` with API credentials, creates a `RequestMessage` object including a `custom_fields` dictionary, sends the message, and then demonstrates retrieving the message to verify the custom fields. Ensure the `solapi` library is installed. ```python from solapi import SolapiMessageService from solapi.model import RequestMessage message_service = SolapiMessageService( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) # Create message with custom metadata message = RequestMessage( from_="01012345678", to="01087654321", text="Your order #12345 has been shipped!", custom_fields={ "order_id": "12345", "customer_id": "CUST789", "campaign": "spring_sale_2025", "priority": "high", "department": "sales" } ) try: response = message_service.send(message) print(f"Message sent with custom tracking data") print(f"Group ID: {response.group_info.group_id}") # Later, retrieve and check custom fields from solapi.model.request.messages.get_messages import GetMessagesRequest query = GetMessagesRequest( group_id=response.group_info.group_id ) messages = message_service.get_messages(query) for msg in messages.data: if msg.custom_fields: print(f"\nRetrieved custom fields:") print(f" Order ID: {msg.custom_fields.get('order_id')}") print(f" Campaign: {msg.custom_fields.get('campaign')}") except Exception as e: print(f"Error: {str(e)}") ``` -------------------------------- ### Handle Single Message Delivery Webhooks with Python Flask Source: https://context7.com/solapi/solapi-python/llms.txt This snippet demonstrates how to set up a Flask web server to receive and parse single message delivery reports via webhook callbacks from Solapi. It uses the `SingleReportPayload` model for validation and iterates through reports to print delivery details. Ensure the `solapi.model.webhook.single_report` and `flask` libraries are installed. ```python from solapi.model.webhook.single_report import SingleReportPayload from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/webhook/single-report', methods=['POST']) def handle_single_report(): """ Webhook endpoint for receiving single message delivery reports SOLAPI sends POST requests with delivery status updates """ try: # Parse incoming webhook data webhook_data = request.get_json() # Validate and parse using Pydantic model reports = SingleReportPayload.model_validate(webhook_data) # Process each report for report in reports.root: data = report.data print(f"\nDelivery Report:") print(f" Event ID: {report.event_data_id}") print(f" Message ID: {data.message_id}") print(f" Group ID: {data.group_id}") print(f" To: {data.to}") print(f" From: {data.from_}") print(f" Type: {data.type}") print(f" Status: {data.status_code}") print(f" Status Message: {data.status_message}") print(f" Processed: {data.date_processed}") print(f" Reported: {data.date_reported}") print(f" Carrier: {data.network_code}") # Access custom fields if any if data.custom_fields: print(f" Custom Fields: {data.custom_fields}") # Update your database with delivery status # update_message_status(data.message_id, data.status_code) # Handle retries if needed if report.retry_count and report.retry_count > 0: print(f" Retry Count: {report.retry_count}") return jsonify({"status": "success"}), 200 except Exception as e: print(f"Webhook error: {str(e)}") return jsonify({"status": "error", "message": str(e)}), 400 if __name__ == '__main__': app.run(port=5000) ``` -------------------------------- ### Cancel Scheduled Message with Solapi Python SDK Source: https://context7.com/solapi/solapi-python/llms.txt This example demonstrates how to schedule a message for future delivery using the Solapi Python SDK and then cancel it before it is sent. It involves creating a `RequestMessage`, configuring a `SendRequestConfig` with a `scheduled_date`, sending the message, and then using `cancel_scheduled_message` with the obtained `group_id`. Ensure the `solapi` library is installed. ```python from datetime import datetime, timedelta from solapi import SolapiMessageService from solapi.model import RequestMessage, SendRequestConfig message_service = SolapiMessageService( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) # Schedule a message for tomorrow tomorrow = datetime.now() + timedelta(days=1) message = RequestMessage( from_="01012345678", to="01087654321", text="This is a scheduled message that might be cancelled." ) config = SendRequestConfig(scheduled_date=tomorrow) try: # Schedule the message response = message_service.send(message, config) group_id = response.group_info.group_id print(f"Message scheduled for: {response.group_info.scheduled_date}") print(f"Group ID: {group_id}") print(f"Status: {response.group_info.status}") # Later, if you need to cancel it... user_cancelled = True # Your business logic if user_cancelled: cancel_response = message_service.cancel_scheduled_message(group_id) print(f"\nMessage cancelled successfully!") print(f"New status: {cancel_response.status}") print(f"Cancelled at: {cancel_response.date_updated}") except Exception as e: print(f"Error: {str(e)}") ``` -------------------------------- ### Send RCS Message with Rich Features Source: https://context7.com/solapi/solapi-python/llms.txt Send Rich Communication Services (RCS) messages with advanced formatting, including images, buttons, and interactive elements. This example demonstrates how to configure various RCS options like brand ID, template ID, image layouts, and button actions (web links, replies). It requires a SolapiMessageService instance and properly configured RCS parameters. ```python from solapi import SolapiMessageService from solapi.model import RequestMessage from solapi.model.rcs.rcs_options import RcsOption, RcsButton, RcsButtonType, RcsMmsType message_service = SolapiMessageService( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) # Configure RCS options rcs_option = RcsOption( brand_id="BRAND123456789", # RCS Brand ID template_id="RCS_TEMPLATE_001", # RCS Template ID mms_type=RcsMmsType.M3, # Image layout (M3 = 3 medium images) copy_allowed=True, # Allow user to copy text commercial_type=True, # Mark as commercial message disable_sms=False, # Enable SMS fallback buttons=[ RcsButton( button_type=RcsButtonType.WL, # Web link button button_name="Visit Website", link="https://example.com" ), RcsButton( button_type=RcsButtonType.REPLY, # Reply button button_name="Contact Us", reply_message="I want to contact" ) ] ) message = RequestMessage( from_="01012345678", to="01087654321", text="Check out our new products! Click below to learn more.", rcs_options=rcs_option ) try: response = message_service.send(message) print(f"RCS message sent!") print(f"Group ID: {response.group_info.group_id}") print(f"Status: {response.group_info.status}") except Exception as e: print(f"Error sending RCS: {str(e)}") ``` -------------------------------- ### Get Groups API Source: https://context7.com/solapi/solapi-python/llms.txt Retrieves a list of message groups, with optional filtering by date range and a limit on the number of results. ```APIDOC ## GET /api/message/groups ### Description Retrieves a list of message groups. This endpoint can optionally filter groups by a specified date range and limit the number of returned groups. ### Method GET ### Endpoint /api/message/groups ### Parameters #### Query Parameters - **start_date** (string) - Optional - The start date for filtering groups (YYYY-MM-DD). - **end_date** (string) - Optional - The end date for filtering groups (YYYY-MM-DD). - **limit** (integer) - Optional - The maximum number of groups to return. ### Request Example ```python query = GetGroupsRequest( start_date="2025-01-01", end_date="2025-01-31", limit=20 ) response = message_service.get_groups(query) ``` ### Response #### Success Response (200) - **group_list** (object) - A dictionary where keys are group IDs and values are group objects containing details like status, dates, message counts, pricing, and logs. #### Response Example ```json { "group_list": { "G4V20250115123456789ABCDEFGH": { "status": "completed", "date_created": "2025-01-15T10:00:00Z", "date_sent": "2025-01-15T10:05:00Z", "date_completed": "2025-01-15T10:10:00Z", "count": { "total": 100, "sent_total": 100, "sent_success": 98, "sent_pending": 0, "registered_failed": 2 }, "price": { "SMS": {"count": 100, "price": 10000} }, "balance": {"cash": 50000}, "point": {"point": 1000}, "log": [ "Processing message GID1...", "Message GID1 sent successfully." ] } } } ``` ``` -------------------------------- ### Get Specific Group Messages API Source: https://context7.com/solapi/solapi-python/llms.txt Retrieves detailed information about all individual messages within a specified message group, enabling granular tracking of message delivery. ```APIDOC ## GET /api/message/group/{group_id}/messages ### Description Retrieves all individual messages belonging to a specific message group. This allows for detailed tracking of each message's delivery status and associated information. ### Method GET ### Endpoint /api/message/group/{group_id}/messages ### Parameters #### Path Parameters - **group_id** (string) - Required - The unique identifier of the message group. ### Request Example ```python group_id = "G4V20250115123456789ABCDEFGH" messages_response = message_service.get_group_messages(group_id) ``` ### Response #### Success Response (200) - **data** (array) - A list of message objects, each containing details such as message ID, recipient, type, status, timestamps, and network information. #### Response Example ```json { "data": [ { "message_id": "M12345", "to": "01012345678", "type": "SMS", "status_code": "200", "status_message": "Success", "date_sent": "2025-01-15T10:05:00Z", "date_completed": "2025-01-15T10:08:00Z", "network_code": "SKT" } ] } ``` ``` -------------------------------- ### Schedule Message Delivery with Solapi Python Source: https://context7.com/solapi/solapi-python/llms.txt Schedules a message to be sent at a future date and time. The message content, recipient, and sender are defined in a RequestMessage object. A SendRequestConfig object is used to specify the scheduled date and time, which can be a datetime object or a formatted string. The example includes how to retrieve the group ID and scheduled time, and comments on how to cancel the scheduled message. ```python from datetime import datetime from solapi import SolapiMessageService from solapi.model import RequestMessage, SendRequestConfig message_service = SolapiMessageService( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) # Create message message = RequestMessage( from_="01012345678", to="01087654321", text="Happy New Year! This is a scheduled message." ) # Configure scheduled delivery # Option 1: Using datetime object config = SendRequestConfig( scheduled_date=datetime(2025, 12, 31, 23, 59, 0) ) # Option 2: Using string format (also supported) # config = SendRequestConfig(scheduled_date="2025-12-31 23:59:00") try: # Schedule the message response = message_service.send(message, config) group_id = response.group_info.group_id scheduled_time = response.group_info.scheduled_date print(f"Message scheduled successfully!") print(f"Group ID: {group_id}") print(f"Will be sent at: {scheduled_time}") print(f"Status: {response.group_info.status}") # Later, if you need to cancel the scheduled message: # cancel_response = message_service.cancel_scheduled_message(group_id) # print(f"Cancelled: {cancel_response.status}") except Exception as e: print(f"Error scheduling message: {str(e)}") ``` -------------------------------- ### Get Message Groups with Filters Source: https://context7.com/solapi/solapi-python/llms.txt Retrieve message groups from Solapi, with options to filter by date range and limit the number of results. This function is useful for managing and analyzing past message campaigns. It requires an initialized SolapiMessageService object. ```python from solapi import SolapiMessageService from solapi.model import GetGroupsRequest message_service = SolapiMessageService( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) # Optional: Filter groups by criteria query = GetGroupsRequest( start_date="2025-01-01", end_date="2025-01-31", limit=20 ) try: # Get groups (or pass None for all recent groups) response = message_service.get_groups(query) print(f"Found {len(response.group_list)} message groups") # Iterate through groups for group_id, group in response.group_list.items(): print(f"\n{'='*50}") print(f"Group ID: {group_id}") print(f"Status: {group.status}") print(f"Created: {group.date_created}") print(f"Sent: {group.date_sent}") print(f"Completed: {group.date_completed}") # Message counts print(f"\nMessage Statistics:") print(f" Total: {group.count.total}") print(f" Sent: {group.count.sent_total}") print(f" Success: {group.count.sent_success}") print(f" Pending: {group.count.sent_pending}") print(f" Failed: {group.count.registered_failed}") # Cost information print(f"\nCost Breakdown:") for msg_type, price_info in group.price.items(): print(f" {msg_type}: {price_info.count} msgs × {price_info.price} won") # Balance after send print(f"\nBalance After Send:") print(f" Cash: {group.balance.cash} won") print(f" Point: {group.point.point} points") # Processing logs if group.log: print(f"\nLogs: {len(group.log)} entries") for log_entry in group.log[:3]: # Show first 3 print(f" {log_entry}") except Exception as e: print(f"Error retrieving groups: {str(e)}") ``` -------------------------------- ### Initialize SOLAPI Message Service Source: https://context7.com/solapi/solapi-python/llms.txt Initializes the main service class with API credentials to access all messaging and query functionality. Requires API key and secret for authentication. ```python from solapi import SolapiMessageService # Initialize with your API credentials from SOLAPI dashboard message_service = SolapiMessageService( api_key="NCSABCDEFGHIJKLMN01234567890", api_secret="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCD" ) # The service is now ready to send messages and make API calls # Base URL is automatically set to https://api.solapi.com ``` -------------------------------- ### Initialize SOLAPI Message Service Source: https://context7.com/solapi/solapi-python/llms.txt Initializes the main service class with API credentials. This is a prerequisite for accessing all messaging and query functionality. ```APIDOC ## Initialize SOLAPI Message Service ### Description Initializes the main service class with API credentials to access all messaging and query functionality. ### Method Initialization (Not an HTTP request) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from solapi import SolapiMessageService message_service = SolapiMessageService( api_key="NCSABCDEFGHIJKLMN01234567890", api_secret="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCD" ) ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Run All SOLAPI Python SDK Tests with Pytest Source: https://github.com/solapi/solapi-python/blob/main/tests/README.md Executes all unit tests defined for the SOLAPI Python SDK using the pytest framework. This provides a comprehensive check of the SDK's functionality. ```bash pytest ``` -------------------------------- ### Run SOLAPI Python SDK Tests with Verbose Output Source: https://github.com/solapi/solapi-python/blob/main/tests/README.md Executes all unit tests for the SOLAPI Python SDK with verbose output enabled via pytest. This provides more detailed information during test execution. ```bash pytest -v ``` -------------------------------- ### Send Kakao Alimtalk with Template using Solapi Python Source: https://context7.com/solapi/solapi-python/llms.txt Sends a Kakao notification message (Alimtalk) using a predefined template and substitutes variables within the template. It requires the Kakao Business Channel ID, template ID, and a dictionary of variables. An option to disable SMS fallback is available. Error handling for the sending process is included. ```python from solapi import SolapiMessageService from solapi.model import RequestMessage from solapi.model.kakao.kakao_option import KakaoOption message_service = SolapiMessageService( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) # Configure Kakao Alimtalk options kakao_option = KakaoOption( pf_id="@yourchannelid", # Kakao Business Channel ID template_id="TEMPLATE_001", # Registered template ID variables={ "#{name}": "김철수", "#{amount}": "50000", "#{date}": "2025-01-15" }, disable_sms=False # Allow SMS fallback if Kakao fails ) message = RequestMessage( from_="01012345678", # Used for SMS fallback to="01087654321", kakao_options=kakao_option ) try: response = message_service.send(message) print(f"Kakao Alimtalk sent!") print(f"Group ID: {response.group_info.group_id}") print(f"Success count: {response.group_info.count.registered_success}") except Exception as e: print(f"Failed to send Kakao message: {str(e)}") ``` -------------------------------- ### Run Specific Test File with Pytest Source: https://github.com/solapi/solapi-python/blob/main/tests/README.md Targets and executes tests within a particular file, such as `test_balance.py`, using pytest. This is useful for focused testing or debugging. ```bash pytest tests/test_balance.py ``` -------------------------------- ### Upload File and Send MMS with Solapi Python Source: https://context7.com/solapi/solapi-python/llms.txt Uploads an image file using Solapi's SDK and sends it as an MMS message. Requires the file path and specifies the upload type. The output includes the file ID for the uploaded file and the group ID and cost for the sent MMS. Error handling for file not found and general exceptions is included. ```python from solapi import SolapiMessageService from solapi.model import RequestMessage from solapi.model.request.storage import FileTypeEnum from os.path import abspath message_service = SolapiMessageService( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) try: # Step 1: Upload the image file file_response = message_service.upload_file( file_path=abspath("images/product.jpg"), upload_type=FileTypeEnum.MMS ) print(f"File uploaded successfully!") print(f"File ID: {file_response.file_id}") # Step 2: Send MMS with the uploaded image message = RequestMessage( from_="01012345678", to="01087654321", subject="New Product Announcement", # Optional MMS subject text="Check out our new product! Special 50% discount this week.", image_id=file_response.file_id # Reference uploaded file ) response = message_service.send(message) print(f"\nMMS sent successfully!") print(f"Group ID: {response.group_info.group_id}") print(f"Cost: {response.group_info.price}") except FileNotFoundError: print("Image file not found. Please check the path.") except Exception as e: print(f"Error: {str(e)}") ``` -------------------------------- ### Send Voice Message with Options - Python Source: https://context7.com/solapi/solapi-python/llms.txt Configures and sends a voice message using the Solapi Python SDK. It allows setting voice options like gender, header/tail messages, reply ranges, and counselor numbers. Requires a SolapiMessageService instance and valid recipient/sender numbers. ```python from solapi import SolapiMessageService from solapi.model.request.messages import RequestMessage, VoiceOption # Initialize the message service with your API credentials message_service = SolapiMessageService( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) # Configure voice options voice_option = VoiceOption( voice_type="FEMALE", # "FEMALE" or "MALE" header_message="Welcome to our service!", # Played before main message tail_message="Thank you for calling.", # Played after main message reply_range=3, # Allow buttons 1-3 counselor_number="15441234" # Allow pressing 0 for counselor ) # Create the message request message = RequestMessage( from_="01012345678", to="01087654321", text="This is the main message. Press 1 for sales, 2 for support, 3 for info.", voice_options=voice_option ) try: response = message_service.send(message) print(f"Voice message sent!") print(f"Group ID: {response.group_info.group_id}") print(f"Cost: {response.group_info.price}") except Exception as e: print(f"Error: {str(e)}") ``` -------------------------------- ### Send Voice Message with TTS using Solapi Python Source: https://context7.com/solapi/solapi-python/llms.txt Initializes the SolapiMessageService to send a voice message using text-to-speech (TTS). This snippet sets up the service with API credentials and would typically be followed by defining the message content and voice options to send the actual voice message. Further details on VoiceOption parameters are expected in subsequent code. ```python from solapi import SolapiMessageService from solapi.model import RequestMessage, VoiceOption message_service = SolapiMessageService( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) ``` -------------------------------- ### Set Environment Variables for SOLAPI API Credentials Source: https://github.com/solapi/solapi-python/blob/main/tests/README.md Configures essential environment variables for authentication and testing with the SOLAPI API. This includes API keys, secret, sender/recipient numbers, and Kakao-specific identifiers. ```bash export SOLAPI_API_KEY="your_api_key" export SOLAPI_API_SECRET="your_api_secret" export SOLAPI_SENDER="your_registered_sender_number" export SOLAPI_RECIPIENT="recipient_phone_number" export SOLAPI_KAKAO_PF_ID="your_kakao_business_channel_id" export SOLAPI_KAKAO_TEMPLATE_ID="your_kakao_template_id" ``` -------------------------------- ### Send Voice Message Source: https://context7.com/solapi/solapi-python/llms.txt This section demonstrates how to send a voice message using the Solapi API. It includes configuring voice options such as voice type, header/tail messages, reply range, and counselor number. ```APIDOC ## POST /api/messages/voice ### Description Sends a voice message with customizable voice options. ### Method POST ### Endpoint /api/messages/voice ### Parameters #### Request Body - **from_** (string) - Required - Sender phone number. - **to** (string) - Required - Recipient phone number. - **text** (string) - Required - The main message content. - **voice_options** (object) - Optional - Configuration for voice playback. - **voice_type** (string) - Required - Voice type: "FEMALE" or "MALE". - **header_message** (string) - Optional - Message played before the main message. - **tail_message** (string) - Optional - Message played after the main message. - **reply_range** (integer) - Optional - The range of buttons allowed for reply (e.g., 3 for buttons 1-3). - **counselor_number** (string) - Optional - Phone number to connect to when a counselor is requested (e.g., pressing 0). ### Request Example ```json { "from_": "01012345678", "to": "01087654321", "text": "This is the main message. Press 1 for sales, 2 for support, 3 for info.", "voice_options": { "voice_type": "FEMALE", "header_message": "Welcome to our service!", "tail_message": "Thank you for calling.", "reply_range": 3, "counselor_number": "15441234" } } ``` ### Response #### Success Response (200) - **group_info** (object) - Information about the sent message group. - **group_id** (string) - The unique identifier for the message group. - **price** (string) - The cost of sending the message. #### Response Example ```json { "group_info": { "group_id": "GRP1234567890", "price": "150" } } ``` ``` -------------------------------- ### Retrieve Message Groups - Python Source: https://context7.com/solapi/solapi-python/llms.txt Queries message groups using the Solapi Python SDK. This is primarily used for tracking bulk message campaigns and accessing their detailed statistics. Requires an initialized SolapiMessageService and appropriate API credentials. ```python from solapi import SolapiMessageService from solapi.model.request.groups.get_groups import GetGroupsRequest message_service = SolapiMessageService( api_key="YOUR_API_API_KEY", api_secret="YOUR_API_SECRET" ) # Example: Querying groups for a specific date range # query = GetGroupsRequest( # start_date="2025-01-01", # end_date="2025-01-31", # limit=10 # ) # try: # response = message_service.get_groups(query) # print(f"Found {len(response.data)} message groups.") # for group in response.data: # print(f"Group ID: {group.group_id}, Status: {group.status}, Created: {group.created_at}") # except Exception as e: # print(f"Error retrieving message groups: {str(e)}") ``` -------------------------------- ### Check Account Balance Source: https://context7.com/solapi/solapi-python/llms.txt Retrieves the current account balance and point information for the Solapi account. ```APIDOC ## GET /api/cash/balance ### Description Retrieves the current cash and point balance of the Solapi account. ### Method GET ### Endpoint /api/cash/balance ### Parameters No parameters required. ### Request Example (No request body or query parameters for this endpoint) ### Response #### Success Response (200) - **balance** (number) - The current cash balance in won. - **point** (number) - The current point balance. #### Response Example ```json { "balance": 500000, "point": 10000 } ``` ``` -------------------------------- ### Check Account Balance - Python Source: https://context7.com/solapi/solapi-python/llms.txt Retrieves the current account balance and point information using the Solapi Python SDK. This function is useful for monitoring account status and triggering alerts for low balances. Requires a SolapiMessageService instance. ```python from solapi import SolapiMessageService message_service = SolapiMessageService( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) try: balance_response = message_service.get_balance() print(f"Account Balance Information:") print(f"Cash Balance: {balance_response.balance:,.0f} won") print(f"Point Balance: {balance_response.point:,.0f} points") # Check if balance is low if balance_response.balance < 10000: print("\nWarning: Low balance! Please recharge your account.") except Exception as e: print(f"Error retrieving balance: {str(e)}") ``` -------------------------------- ### Retrieve Message Groups Source: https://context7.com/solapi/solapi-python/llms.txt Query message groups to track bulk message campaigns and their detailed statistics. Supports filtering and pagination. ```APIDOC ## GET /api/groups ### Description Retrieves a list of message groups with filtering and pagination options. ### Method GET ### Endpoint /api/groups ### Parameters #### Query Parameters - **limit** (integer) - Optional - Number of results to return per page. - **start_key** (string) - Optional - Pagination key for fetching the next page. - **group_id** (string) - Optional - Filter by specific group ID. - **name** (string) - Optional - Filter by group name. - **status** (string) - Optional - Filter by group status (e.g., "sending", "completed"). - **start_created_at** (string) - Optional - Start date for filtering by creation date (YYYY-MM-DD). - **end_created_at** (string) - Optional - End date for filtering by creation date (YYYY-MM-DD). ### Request Example ```json { "limit": 20, "status": "completed" } ``` ### Response #### Success Response (200) - **data** (array) - An array of message group objects. - **group_id** (string) - Unique identifier for the message group. - **name** (string) - Name of the message group. - **total_messages** (integer) - Total number of messages in the group. - **total_price** (string) - Total cost of messages in the group. - **status** (string) - Status of the message group. - **created_at** (string) - Timestamp when the group was created. - **next_key** (string) - Pagination key for the next page of results, or null if this is the last page. #### Response Example ```json { "data": [ { "group_id": "GRP987654321", "name": "Marketing Campaign Q1", "total_messages": 1000, "total_price": "15000", "status": "completed", "created_at": "2025-01-10T14:00:00Z" } ], "next_key": "ANOTHER_PAGINATION_KEY_XYZ" } ``` ``` -------------------------------- ### Send Bulk Messages with SOLAPI Python SDK Configuration Source: https://context7.com/solapi/solapi-python/llms.txt Sends multiple messages in a single API call, allowing duplicate phone numbers and detailed message lists in the response. Requires a list of messages and optional configuration settings. ```python from solapi import SolapiMessageService from solapi.model import RequestMessage, SendRequestConfig message_service = SolapiMessageService( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) # Create multiple messages for different recipients messages = [ RequestMessage(from_="01012345678", to="01011111111", text="First message"), RequestMessage(from_="01012345678", to="01022222222", text="Second message"), RequestMessage(from_="01012345678", to="01011111111", text="Another to same number"), ] # Configure send options config = SendRequestConfig( allow_duplicates=True, # Allow same phone number multiple times show_message_list=True # Include individual message details in response ) # Send all messages at once try: response = message_service.send(messages, config) print(f"Group ID: {response.group_info.group_id}") print(f"Total sent: {response.group_info.count.total}") # Check for any failed messages if response.failed_message_list: print("\nFailed messages:") for failed in response.failed_message_list: print(f" To: {failed.message.to}") print(f" Reason: {failed.error.message}") print(f" Error code: {failed.error.error_code}") # Access individual message results if show_message_list=True if response.message_list: for msg in response.message_list: print(f"Message ID: {msg.message_id}, Status: {msg.status_code}") except Exception as e: print(f"Error: {str(e)}") ``` -------------------------------- ### Run Specific Test Case with Pytest Source: https://github.com/solapi/solapi-python/blob/main/tests/README.md Executes a single, isolated test case, like `test_send_sms` within the `TestSimpleSend` class, using pytest. This allows for granular testing of specific functionalities. ```bash pytest tests/test_simple_send.py::TestSimpleSend::test_send_sms ``` -------------------------------- ### Send Bulk Messages with Configuration Source: https://context7.com/solapi/solapi-python/llms.txt Sends multiple messages in a single API call, with options to allow duplicate phone numbers and include detailed message lists in the response. ```APIDOC ## Send Bulk Messages with Configuration ### Description Send multiple messages in a single API call with duplicate phone number allowance and detailed message list. ### Method POST (Implicitly via SDK method) ### Endpoint /message/send (Implicitly via SDK method) ### Parameters #### Request Body (Implicit via `RequestMessage` objects and `SendRequestConfig`) - **messages** (array of `RequestMessage` objects) - Required - A list of message objects, each containing sender, recipient, and text. - **from_** (string) - Required - Registered sender phone number. - **to** (string) - Required - Recipient phone number. - **text** (string) - Required - The content of the message. - **config** (`SendRequestConfig` object) - Optional - Configuration for the send request. - **allow_duplicates** (boolean) - Optional - If true, allows sending multiple messages to the same phone number within the same request. Defaults to false. - **show_message_list** (boolean) - Optional - If true, includes details for each individual message in the response. Defaults to false. ### Request Example ```python from solapi import SolapiMessageService from solapi.model import RequestMessage, SendRequestConfig message_service = SolapiMessageService( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) messages = [ RequestMessage(from_="01012345678", to="01011111111", text="First message"), RequestMessage(from_="01012345678", to="01022222222", text="Second message"), RequestMessage(from_="01012345678", to="01011111111", text="Another to same number"), ] config = SendRequestConfig( allow_duplicates=True, show_message_list=True ) try: response = message_service.send(messages, config) print(f"Group ID: {response.group_info.group_id}") print(f"Total sent: {response.group_info.count.total}") if response.failed_message_list: print("\nFailed messages:") for failed in response.failed_message_list: print(f" To: {failed.message.to}") print(f" Reason: {failed.error.message}") print(f" Error code: {failed.error.error_code}") if response.message_list: for msg in response.message_list: print(f"Message ID: {msg.message_id}, Status: {msg.status_code}") except Exception as e: print(f"Error: {str(e)}") ``` ### Response #### Success Response (200) - **group_info** (object) - Information about the message sending group. - **group_id** (string) - Unique identifier for the message group. - **count** (object) - Counts of messages sent. - **total** (integer) - Total number of messages attempted. - **balance** (object) - Remaining account balance. - **cash** (integer) - Remaining cash balance in won. - **message_list** (array of objects) - List of individual message details (only if `show_message_list` is true). - **message_id** (string) - Unique identifier for the message. - **status_code** (string) - Status code of the message. - **success_code** (string) - Success code of the message. - **status_name** (string) - Human-readable status name. - **custom_id** (string or null) - Custom identifier for the message. - **created_at** (string) - Timestamp when the message was created. - **failed_message_list** (array of objects) - List of failed message details. - **message** (object) - The original message details that failed. - **to** (string) - Recipient phone number. - **error** (object) - Error details for the failed message. - **message** (string) - Error message. - **error_code** (string) - Error code. #### Response Example ```json { "group_info": { "group_id": "gpk66xxxxxxxxx", "header": {}, "scheduled_time": null, "completed_time": null, "status": "finished", "message_count": { "total": 3, "registered_success": 3, "registered_failed": 0, "sent_success": 3, "sent_failed": 0, "approved": 0, "rejected": 0, "cancel_requested": 0, "cancelled": 0, "pending": 0, "in_progress": 0, "unapproved": 0, "unregistered": 0 }, "balance": { "point": 0, "cash": 999999 } }, "message_list": [ { "message_id": "imx66xxxxxxxxx", "status_code": "2000", "success_code": "NORMAL", "status_name": "Success", "custom_id": null, "created_at": "2023-10-27T10:00:00.000Z" }, { "message_id": "imx66xxxxxxxxx", "status_code": "2000", "success_code": "NORMAL", "status_name": "Success", "custom_id": null, "created_at": "2023-10-27T10:00:00.000Z" }, { "message_id": "imx66xxxxxxxxx", "status_code": "2000", "success_code": "NORMAL", "status_name": "Success", "custom_id": null, "created_at": "2023-10-27T10:00:00.000Z" } ], "failed_message_list": [] } ``` ``` -------------------------------- ### Query Message History with Filters - Python Source: https://context7.com/solapi/solapi-python/llms.txt Retrieves message history using the Solapi Python SDK with various filters. Supports filtering by date range, sender/receiver numbers, message type, and pagination. Requires a SolapiMessageService instance and valid API credentials. ```python from solapi import SolapiMessageService from solapi.model.request.messages.get_messages import GetMessagesRequest from solapi.model.message_type import MessageType message_service = SolapiMessageService( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) # Create query with filters query = GetMessagesRequest( start_date="2025-01-01", # Start date (YYYY-MM-DD) end_date="2025-01-31", # End date from_="01012345678", # Filter by sender type=MessageType.SMS, # Filter by message type limit=50, # Limit results per page # start_key="pagination_key" # For next page ) try: response = message_service.get_messages(query) print(f"Total messages found: {len(response.data)}") print(f"Next page key: {response.next_key}") # Process each message for message in response.data: print(f"\nMessage ID: {message.message_id}") print(f" To: {message.to}") print(f" From: {message.from_}") print(f" Text: {message.text}") print(f" Type: {message.type}") print(f" Status: {message.status_code}") print(f" Sent: {message.date_sent}") print(f" Completed: {message.date_completed}") # Access custom fields if any if message.custom_fields: print(f" Custom fields: {message.custom_fields}") # Paginate to next page if needed if response.next_key: next_query = GetMessagesRequest( start_date="2025-01-01", end_date="2025-01-31", start_key=response.next_key, limit=50 ) next_response = message_service.get_messages(next_query) print(f"\nNext page has {len(next_response.data)} messages") except Exception as e: print(f"Error querying messages: {str(e)}") ``` -------------------------------- ### Query Message History with Filters Source: https://context7.com/solapi/solapi-python/llms.txt Retrieve message history with flexible filtering by date range, phone numbers, message type, and status. Supports pagination for large result sets. ```APIDOC ## GET /api/messages ### Description Retrieves message history with various filtering options and supports pagination. ### Method GET ### Endpoint /api/messages ### Parameters #### Query Parameters - **start_date** (string) - Optional - Start date for filtering messages (YYYY-MM-DD). - **end_date** (string) - Optional - End date for filtering messages (YYYY-MM-DD). - **from_** (string) - Optional - Filter by sender phone number. - **to** (string) - Optional - Filter by recipient phone number. - **type** (string) - Optional - Filter by message type (e.g., "SMS", "MMS", "ATA"). - **status_code** (string) - Optional - Filter by message status code. - **limit** (integer) - Optional - Number of results to return per page (default is usually 20, max 100). - **start_key** (string) - Optional - A pagination key to retrieve the next page of results. ### Request Example ```json { "start_date": "2025-01-01", "end_date": "2025-01-31", "from_": "01012345678", "type": "SMS", "limit": 50 } ``` ### Response #### Success Response (200) - **data** (array) - An array of message objects. - **message_id** (string) - Unique identifier for the message. - **to** (string) - Recipient phone number. - **from_** (string) - Sender phone number. - **text** (string) - The message content. - **type** (string) - The type of message (e.g., SMS). - **status_code** (string) - The status code of the message. - **date_sent** (string) - Timestamp when the message was sent. - **date_completed** (string) - Timestamp when the message status was last updated. - **custom_fields** (object) - Optional - Any custom fields associated with the message. - **next_key** (string) - A key for fetching the next page of results, or null if this is the last page. #### Response Example ```json { "data": [ { "message_id": "MSG1234567890", "to": "01087654321", "from_": "01012345678", "text": "Hello there!", "type": "SMS", "status_code": "2000", "date_sent": "2025-01-15T10:30:00Z", "date_completed": "2025-01-15T10:31:00Z", "custom_fields": {} } ], "next_key": "PAGINATION_KEY_ABCDEF" } ``` ```