-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsms.py
More file actions
331 lines (271 loc) · 11.7 KB
/
sms.py
File metadata and controls
331 lines (271 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import logging
from datetime import datetime
from typing import TYPE_CHECKING, List, Optional
from ..exceptions import DevoValidationException
from ..utils import validate_email, validate_phone_number, validate_required_string
from .base import BaseResource
if TYPE_CHECKING:
from ..models.sms import AvailableNumbersResponse, NumberPurchaseResponse, SendersListResponse, SMSQuickSendResponse
logger = logging.getLogger(__name__)
class SMSResource(BaseResource):
"""
SMS resource for sending messages and managing phone numbers.
This resource provides access to SMS functionality including:
- Sending SMS messages via quick-send
- Managing senders and phone numbers
- Purchasing new phone numbers
- Listing available numbers
Examples:
Send SMS:
>>> response = client.sms.send_sms(
... recipient="+1234567890",
... message="Hello World!",
... sender="+0987654321"
... )
Get senders:
>>> senders = client.sms.get_senders()
>>> for sender in senders.senders:
... print(f"Sender: {sender.phone_number}")
Buy number:
>>> number = client.sms.buy_number(
... region="US",
... number="+1234567890",
... number_type="mobile",
... agency_authorized_representative="Jane Doe",
... agency_representative_email="jane.doe@company.com"
... )
List available numbers:
>>> numbers = client.sms.get_available_numbers(
... region="US",
... limit=10,
... number_type="mobile"
... )
"""
def send_sms(
self,
recipient: str,
message: str,
sender: str,
hirvalidation: bool = True,
sandbox: bool = False,
) -> "SMSQuickSendResponse":
"""
Send an SMS message using the quick-send API.
Args:
recipient: The recipient's phone number in E.164 format
message: The SMS message content
sender: The sender phone number or sender ID
hirvalidation: Enable HIR validation (default: True)
sandbox: Use sandbox environment for testing (default: False)
Returns:
SMSQuickSendResponse: The sent message details including ID and status
Raises:
DevoValidationException: If required fields are invalid
DevoAPIException: If the API returns an error
Example:
>>> response = client.sms.send_sms(
... recipient="+1234567890",
... message="Hello World!",
... sender="+0987654321"
... )
>>> print(f"Message ID: {response.id}")
>>> print(f"Status: {response.status}")
"""
# Validate inputs
recipient = validate_phone_number(recipient)
message = validate_required_string(message, "message")
sender = validate_required_string(sender, "sender")
logger.info(f"Sending SMS to {recipient} from {sender}")
# Prepare request data according to API spec
from ..models.sms import SMSQuickSendRequest
request_data = SMSQuickSendRequest(
sender=sender,
recipient=recipient,
message=message,
hirvalidation=hirvalidation,
)
# Send request to the exact API endpoint
response = self.client.post("user-api/sms/quick-send", json=request_data.dict(), sandbox=sandbox)
# Parse response according to API spec
from ..models.sms import SMSQuickSendResponse
result = SMSQuickSendResponse.model_validate(response.json())
logger.info(f"SMS sent successfully with ID: {result.id}")
return result
def get_senders(self, sandbox: bool = False) -> "SendersListResponse":
"""
Retrieve the list of available senders for the account.
Args:
sandbox: Use sandbox environment for testing (default: False)
Returns:
SendersListResponse: List of available senders with their details
Raises:
DevoAPIException: If the API returns an error
Example:
>>> senders = client.sms.get_senders()
>>> for sender in senders.senders:
... print(f"Sender: {sender.phone_number} (Type: {sender.type})")
... print(f"Is Test: {sender.istest}")
"""
logger.info("Fetching available senders")
# Send request to the exact API endpoint
response = self.client.get("user-api/me/senders", sandbox=sandbox)
# Parse response according to API spec
from ..models.sms import SendersListResponse
result = SendersListResponse.model_validate(response.json())
logger.info(f"Retrieved {len(result.senders)} senders")
return result
def buy_number(
self,
region: str,
number: str,
number_type: str,
agency_authorized_representative: str,
agency_representative_email: str,
is_longcode: bool = True,
agreement_last_sent_date: Optional[datetime] = None,
is_automated_enabled: bool = True,
sandbox: bool = False,
) -> "NumberPurchaseResponse":
"""
Purchase a phone number.
Args:
region: Region/country code for the number
number: Phone number to purchase
number_type: Type of number (mobile, landline, etc.)
agency_authorized_representative: Name of authorized representative
agency_representative_email: Email of authorized representative
is_longcode: Whether this is a long code number (default: True)
agreement_last_sent_date: Last date agreement was sent (optional)
is_automated_enabled: Whether automated messages are enabled (default: True)
sandbox: Use sandbox environment for testing (default: False)
Returns:
NumberPurchaseResponse: Details of the purchased number including features
Raises:
DevoValidationException: If required fields are invalid
DevoAPIException: If the API returns an error
Example:
>>> number = client.sms.buy_number(
... region="US",
... number="+1234567890",
... number_type="mobile",
... agency_authorized_representative="Jane Doe",
... agency_representative_email="jane.doe@company.com"
... )
>>> print(f"Purchased number with {len(number.features)} features")
"""
# Validate inputs
region = validate_required_string(region, "region")
number = validate_phone_number(number)
number_type = validate_required_string(number_type, "number_type")
agency_authorized_representative = validate_required_string(
agency_authorized_representative, "agency_authorized_representative"
)
agency_representative_email = validate_email(agency_representative_email)
logger.info(f"Purchasing number {number} in region {region}")
# Prepare request data according to API spec
from ..models.sms import NumberPurchaseRequest
request_data = NumberPurchaseRequest(
region=region,
number=number,
number_type=number_type,
is_longcode=is_longcode,
agreement_last_sent_date=agreement_last_sent_date,
agency_authorized_representative=agency_authorized_representative,
agency_representative_email=agency_representative_email,
is_automated_enabled=is_automated_enabled,
)
# Send request to the exact API endpoint
response = self.client.post("user-api/numbers/buy", json=request_data.dict(exclude_none=True))
# Parse response according to API spec
from ..models.sms import NumberPurchaseResponse
result = NumberPurchaseResponse.model_validate(response.json())
feature_count = len(result.features) if result.features else 0
logger.info(f"Number purchased successfully with {feature_count} features")
return result
def get_available_numbers(
self,
page: Optional[int] = None,
limit: Optional[int] = None,
capabilities: Optional[List[str]] = None,
type: Optional[str] = None,
prefix: Optional[str] = None,
region: str = "US",
sandbox: bool = False,
) -> "AvailableNumbersResponse":
"""
Get available phone numbers for purchase.
Args:
page: The page number (optional)
limit: The page limit (optional)
capabilities: Filter by capabilities (optional)
type: Filter by type (optional)
prefix: Filter by prefix (optional)
region: Filter by region (Country ISO Code), default: "US"
sandbox: Use sandbox environment for testing (default: False)
Returns:
AvailableNumbersResponse: List of available numbers with their features
Raises:
DevoValidationException: If required fields are invalid
DevoAPIException: If the API returns an error
Example:
>>> numbers = client.sms.get_available_numbers(
... region="US",
... limit=10,
... type="mobile"
... )
>>> for number_info in numbers.numbers:
... for feature in number_info.features:
... print(f"Number: {feature.phone_number}")
... print(f"Cost: {feature.cost_information.monthly_cost}")
"""
logger.info(f"Fetching available numbers for region {region}")
# Prepare query parameters
params = {"region": region}
if page is not None:
params["page"] = page
if limit is not None:
params["limit"] = limit
if capabilities is not None:
params["capabilities"] = capabilities
if type is not None:
params["type"] = type
if prefix is not None:
params["prefix"] = prefix
# Send request to the exact API endpoint
response = self.client.get("user-api/numbers", params=params)
# Parse response according to API spec - API returns direct array
from ..models.sms import AvailableNumbersResponse
response_data = response.json()
if isinstance(response_data, list):
# API returns direct array, use custom parser
result = AvailableNumbersResponse.parse_from_list(response_data)
else:
# Fallback to normal parsing if API changes
result = AvailableNumbersResponse.model_validate(response_data)
logger.info(f"Retrieved {len(result.numbers)} available numbers")
return result
# Legacy methods for backward compatibility
def send(
self, to: str, body: str, from_: Optional[str] = None, sandbox: bool = False, **kwargs
) -> "SMSQuickSendResponse":
"""
Legacy method for sending SMS (backward compatibility).
Args:
to: The recipient's phone number in E.164 format
body: The message body text
from_: The sender's phone number (optional)
sandbox: Use sandbox environment for testing (default: False)
**kwargs: Additional parameters (ignored for compatibility)
Returns:
SMSQuickSendResponse: The sent message details
Note:
This method is deprecated. Use send_sms() instead.
"""
if not from_:
raise DevoValidationException("Sender (from_) is required for SMS sending")
return self.send_sms(
recipient=to,
message=body,
sender=from_,
hirvalidation=kwargs.get("hirvalidation", True),
)