0
# Core Communications
1
2
Fundamental telecommunications capabilities including SMS/MMS messaging, voice calls, phone number management, and basic account operations. These APIs form the core of Twilio's communication platform.
3
4
## Capabilities
5
6
### SMS and MMS Messaging
7
8
Send and manage text and multimedia messages. Supports bulk messaging, delivery status tracking, and media attachments.
9
10
```python { .api }
11
class MessageInstance:
12
"""Represents a sent or received message"""
13
sid: str # Unique message identifier
14
account_sid: str # Account that sent the message
15
from_: str # Sender phone number
16
to: str # Recipient phone number
17
body: str # Message text content
18
media_url: list # URLs of attached media files
19
status: str # Message status
20
direction: str # 'inbound' or 'outbound'
21
date_created: datetime # When message was created
22
date_sent: datetime # When message was sent
23
date_updated: datetime # Last status update
24
price: str # Cost of the message
25
error_code: int # Error code if failed
26
error_message: str # Error description if failed
27
num_segments: int # Number of segments for long messages
28
messaging_service_sid: str # Service used to send
29
30
class MessageList:
31
def create(
32
self,
33
to: str,
34
from_: str = None,
35
messaging_service_sid: str = None,
36
body: str = None,
37
media_url: list = None,
38
status_callback: str = None,
39
application_sid: str = None,
40
max_price: str = None,
41
provide_feedback: bool = None,
42
attempt: int = None,
43
validity_period: int = None,
44
force_delivery: bool = None,
45
content_retention: str = None,
46
address_retention: str = None,
47
smart_encoded: bool = None,
48
persistent_action: list = None,
49
shorten_urls: bool = None,
50
schedule_type: str = None,
51
send_at: datetime = None,
52
send_as_mms: bool = None,
53
content_variables: dict = None
54
) -> MessageInstance:
55
"""
56
Send a new message.
57
58
Args:
59
to (str): Destination phone number
60
from_ (str): Sender phone number (or messaging service SID)
61
messaging_service_sid (str): Messaging service to use
62
body (str): Message text (up to 1600 characters)
63
media_url (list): URLs of media files to attach
64
status_callback (str): Webhook URL for delivery updates
65
application_sid (str): TwiML application for handling
66
max_price (str): Maximum price willing to pay
67
provide_feedback (bool): Enable delivery feedback
68
attempt (int): Number of send attempts
69
validity_period (int): Message expiration in seconds
70
force_delivery (bool): Attempt delivery even if risky
71
content_retention (str): Content retention policy
72
address_retention (str): Address retention policy
73
smart_encoded (bool): Enable smart encoding
74
persistent_action (list): Actions for message persistence
75
shorten_urls (bool): Automatically shorten URLs
76
schedule_type (str): Scheduling type for future messages
77
send_at (datetime): When to send the message
78
send_as_mms (bool): Force MMS even without media
79
content_variables (dict): Variables for content templates
80
81
Returns:
82
MessageInstance: Created message object
83
"""
84
85
def list(
86
self,
87
to: str = None,
88
from_: str = None,
89
date_sent_before: date = None,
90
date_sent: date = None,
91
date_sent_after: date = None,
92
limit: int = None,
93
page_size: int = None
94
) -> Iterator[MessageInstance]:
95
"""
96
List messages with optional filtering.
97
98
Args:
99
to (str): Filter by recipient
100
from_ (str): Filter by sender
101
date_sent_before (date): Messages sent before this date
102
date_sent (date): Messages sent on this date
103
date_sent_after (date): Messages sent after this date
104
limit (int): Maximum number of messages to return
105
page_size (int): Number of messages per page
106
107
Returns:
108
Iterator[MessageInstance]: Message list iterator
109
"""
110
111
def get(self, sid: str) -> MessageContext:
112
"""Get a specific message by SID for update/delete operations"""
113
114
def delete(self) -> bool:
115
"""Delete the message (returns True if successful)"""
116
117
def update(
118
self,
119
body: str = None,
120
status: str = None
121
) -> MessageInstance:
122
"""
123
Update message properties.
124
125
Args:
126
body (str): Updated message body
127
status (str): Updated status ('canceled' to cancel)
128
129
Returns:
130
MessageInstance: Updated message
131
"""
132
```
133
134
SMS/MMS usage examples:
135
136
```python
137
# Send basic SMS
138
message = client.messages.create(
139
body="Hello from Twilio!",
140
from_="+15551234567",
141
to="+15559876543"
142
)
143
print(f"Message SID: {message.sid}")
144
145
# Send MMS with image
146
message = client.messages.create(
147
body="Check out this image!",
148
from_="+15551234567",
149
to="+15559876543",
150
media_url=["https://example.com/image.jpg"]
151
)
152
153
# Send using messaging service
154
message = client.messages.create(
155
body="Service message",
156
messaging_service_sid="MGxxxxx",
157
to="+15559876543"
158
)
159
160
# Schedule message for later
161
from datetime import datetime, timedelta
162
send_time = datetime.now() + timedelta(hours=1)
163
164
message = client.messages.create(
165
body="Scheduled message",
166
from_="+15551234567",
167
to="+15559876543",
168
schedule_type="fixed",
169
send_at=send_time
170
)
171
172
# List recent messages
173
for message in client.messages.list(limit=20):
174
print(f"{message.from_} -> {message.to}: {message.body}")
175
176
# Get specific message
177
message = client.messages.get("SMxxxxx").fetch()
178
print(f"Status: {message.status}")
179
180
# Cancel scheduled message
181
client.messages.get("SMxxxxx").update(status="canceled")
182
```
183
184
### Voice Calls
185
186
Make and manage voice calls with support for TwiML, call recording, conferencing, and real-time call control.
187
188
```python { .api }
189
class CallInstance:
190
"""Represents a voice call"""
191
sid: str # Unique call identifier
192
account_sid: str # Account that initiated the call
193
from_: str # Caller's phone number
194
to: str # Called phone number
195
status: str # Call status
196
direction: str # 'inbound' or 'outbound'
197
duration: int # Call duration in seconds
198
price: str # Cost of the call
199
date_created: datetime # When call was initiated
200
date_updated: datetime # Last status update
201
start_time: datetime # When call started
202
end_time: datetime # When call ended
203
parent_call_sid: str # Parent call for transfers
204
phone_number_sid: str # Phone number used
205
forwarded_from: str # Original caller if forwarded
206
caller_name: str # Caller ID name
207
uri: str # API resource URI
208
209
class CallList:
210
def create(
211
self,
212
to: str,
213
from_: str,
214
url: str = None,
215
twiml: str = None,
216
application_sid: str = None,
217
method: str = None,
218
fallback_url: str = None,
219
fallback_method: str = None,
220
status_callback: str = None,
221
status_callback_event: list = None,
222
status_callback_method: str = None,
223
send_digits: str = None,
224
timeout: int = None,
225
record: bool = None,
226
recording_channels: str = None,
227
recording_status_callback: str = None,
228
recording_status_callback_method: str = None,
229
sip_auth_username: str = None,
230
sip_auth_password: str = None,
231
machine_detection: str = None,
232
machine_detection_timeout: int = None,
233
recording_status_callback_event: list = None,
234
trim: str = None,
235
caller_id: str = None,
236
machine_detection_speech_threshold: int = None,
237
machine_detection_speech_end_threshold: int = None,
238
machine_detection_silence_timeout: int = None,
239
async_amd: str = None,
240
async_amd_status_callback: str = None,
241
async_amd_status_callback_method: str = None,
242
byoc: str = None,
243
call_reason: str = None,
244
call_token: str = None,
245
recording_track: str = None,
246
time_limit: int = None
247
) -> CallInstance:
248
"""
249
Initiate a new voice call.
250
251
Args:
252
to (str): Destination phone number or SIP address
253
from_ (str): Caller phone number
254
url (str): TwiML URL to execute
255
twiml (str): TwiML instructions to execute
256
application_sid (str): TwiML application to use
257
method (str): HTTP method for URL ('GET' or 'POST')
258
fallback_url (str): Fallback URL if primary fails
259
fallback_method (str): HTTP method for fallback
260
status_callback (str): Webhook for call status updates
261
status_callback_event (list): Events to report
262
status_callback_method (str): HTTP method for status callback
263
send_digits (str): DTMF digits to send after connect
264
timeout (int): Ring timeout in seconds
265
record (bool): Record the call
266
recording_channels (str): 'mono' or 'dual'
267
recording_status_callback (str): Recording status webhook
268
machine_detection (str): 'Enable' answering machine detection
269
machine_detection_timeout (int): AMD timeout in seconds
270
trim (str): 'trim-silence' to remove silence
271
caller_id (str): Caller ID to display
272
time_limit (int): Maximum call duration in seconds
273
274
Returns:
275
CallInstance: Created call object
276
"""
277
278
def list(
279
self,
280
to: str = None,
281
from_: str = None,
282
parent_call_sid: str = None,
283
status: str = None,
284
start_time_before: datetime = None,
285
start_time: datetime = None,
286
start_time_after: datetime = None,
287
end_time_before: datetime = None,
288
end_time: datetime = None,
289
end_time_after: datetime = None,
290
limit: int = None,
291
page_size: int = None
292
) -> Iterator[CallInstance]:
293
"""List calls with optional filtering"""
294
295
def update(
296
self,
297
url: str = None,
298
method: str = None,
299
status: str = None,
300
fallback_url: str = None,
301
fallback_method: str = None,
302
status_callback: str = None,
303
status_callback_method: str = None,
304
twiml: str = None,
305
time_limit: int = None
306
) -> CallInstance:
307
"""
308
Update an in-progress call.
309
310
Args:
311
url (str): New TwiML URL to execute
312
method (str): HTTP method for URL
313
status (str): 'canceled' or 'completed' to end call
314
twiml (str): New TwiML to execute
315
time_limit (int): New maximum duration in seconds
316
317
Returns:
318
CallInstance: Updated call object
319
"""
320
```
321
322
Voice call examples:
323
324
```python
325
# Make basic call with TwiML URL
326
call = client.calls.create(
327
to="+15559876543",
328
from_="+15551234567",
329
url="http://demo.twilio.com/docs/voice.xml"
330
)
331
print(f"Call SID: {call.sid}")
332
333
# Make call with inline TwiML
334
call = client.calls.create(
335
to="+15559876543",
336
from_="+15551234567",
337
twiml='<Response><Say>Hello World</Say></Response>'
338
)
339
340
# Make call with recording
341
call = client.calls.create(
342
to="+15559876543",
343
from_="+15551234567",
344
url="http://example.com/twiml",
345
record=True,
346
recording_status_callback="http://example.com/recording"
347
)
348
349
# Make call with answering machine detection
350
call = client.calls.create(
351
to="+15559876543",
352
from_="+15551234567",
353
url="http://example.com/twiml",
354
machine_detection="Enable",
355
machine_detection_timeout=30
356
)
357
358
# List recent calls
359
for call in client.calls.list(limit=20):
360
print(f"{call.from_} -> {call.to}: {call.status} ({call.duration}s)")
361
362
# Update in-progress call
363
client.calls.get("CAxxxxx").update(
364
url="http://example.com/new-twiml"
365
)
366
367
# Hang up call
368
client.calls.get("CAxxxxx").update(status="completed")
369
```
370
371
### Phone Number Management
372
373
Manage phone numbers including purchasing available numbers, configuring incoming numbers, and handling caller ID verification.
374
375
```python { .api }
376
class IncomingPhoneNumberInstance:
377
"""Represents a purchased phone number"""
378
sid: str # Phone number SID
379
account_sid: str # Owning account
380
phone_number: str # The phone number (+E.164 format)
381
friendly_name: str # Human-readable name
382
voice_url: str # Voice webhook URL
383
voice_method: str # Voice webhook HTTP method
384
voice_fallback_url: str # Voice fallback URL
385
voice_fallback_method: str # Voice fallback method
386
voice_caller_id_lookup: bool # Enable caller ID lookup
387
sms_url: str # SMS webhook URL
388
sms_method: str # SMS webhook HTTP method
389
sms_fallback_url: str # SMS fallback URL
390
sms_fallback_method: str # SMS fallback method
391
status_callback: str # Status callback URL
392
status_callback_method: str # Status callback method
393
voice_application_sid: str # Voice TwiML application
394
sms_application_sid: str # SMS TwiML application
395
trunk_sid: str # SIP trunk SID
396
emergency_status: str # E911 registration status
397
emergency_address_sid: str # E911 address SID
398
date_created: datetime # Purchase date
399
date_updated: datetime # Last update
400
401
class AvailablePhoneNumberInstance:
402
"""Represents an available phone number for purchase"""
403
phone_number: str # The available phone number
404
friendly_name: str # Human-readable name
405
locality: str # City/locality
406
region: str # State/region
407
postal_code: str # ZIP/postal code
408
iso_country: str # ISO country code
409
address_requirements: str # Address requirements
410
beta: bool # Is beta number
411
capabilities: dict # SMS/voice/MMS capabilities
412
rate_center: str # Telecom rate center
413
latitude: float # Geographic latitude
414
longitude: float # Geographic longitude
415
416
class IncomingPhoneNumberList:
417
def create(
418
self,
419
phone_number: str = None,
420
area_code: str = None,
421
friendly_name: str = None,
422
voice_url: str = None,
423
voice_method: str = None,
424
voice_fallback_url: str = None,
425
voice_fallback_method: str = None,
426
voice_caller_id_lookup: bool = None,
427
voice_application_sid: str = None,
428
sms_url: str = None,
429
sms_method: str = None,
430
sms_fallback_url: str = None,
431
sms_fallback_method: str = None,
432
sms_application_sid: str = None,
433
status_callback: str = None,
434
status_callback_method: str = None,
435
address_sid: str = None,
436
emergency_status: str = None,
437
emergency_address_sid: str = None,
438
trunk_sid: str = None,
439
identity_sid: str = None,
440
bundle_sid: str = None
441
) -> IncomingPhoneNumberInstance:
442
"""
443
Purchase and configure a phone number.
444
445
Args:
446
phone_number (str): Specific number to purchase
447
area_code (str): Desired area code if no specific number
448
friendly_name (str): Human-readable name
449
voice_url (str): Webhook URL for voice calls
450
voice_method (str): HTTP method for voice webhook
451
voice_application_sid (str): TwiML app for voice
452
sms_url (str): Webhook URL for SMS
453
sms_method (str): HTTP method for SMS webhook
454
sms_application_sid (str): TwiML app for SMS
455
emergency_address_sid (str): E911 address
456
457
Returns:
458
IncomingPhoneNumberInstance: Purchased phone number
459
"""
460
461
class AvailablePhoneNumberCountryList:
462
def local(self) -> LocalList:
463
"""Search local phone numbers"""
464
465
def toll_free(self) -> TollFreeList:
466
"""Search toll-free numbers"""
467
468
def mobile(self) -> MobileList:
469
"""Search mobile numbers"""
470
471
def list(
472
self,
473
area_code: str = None,
474
contains: str = None,
475
sms_enabled: bool = None,
476
mms_enabled: bool = None,
477
voice_enabled: bool = None,
478
exclude_all_address_required: bool = None,
479
exclude_local_address_required: bool = None,
480
exclude_foreign_address_required: bool = None,
481
beta: bool = None,
482
near_number: str = None,
483
near_lat_long: str = None,
484
distance: int = None,
485
in_postal_code: str = None,
486
in_locality: str = None,
487
in_region: str = None,
488
in_rate_center: str = None,
489
in_lata: str = None,
490
limit: int = None
491
) -> Iterator[AvailablePhoneNumberInstance]:
492
"""Search available phone numbers with filters"""
493
```
494
495
Phone number management examples:
496
497
```python
498
# Search for available local numbers
499
available_numbers = client.available_phone_numbers("US").local.list(
500
area_code="415",
501
sms_enabled=True,
502
voice_enabled=True,
503
limit=10
504
)
505
506
for number in available_numbers:
507
print(f"Available: {number.phone_number} in {number.locality}")
508
509
# Purchase a specific number
510
phone_number = client.incoming_phone_numbers.create(
511
phone_number="+14155551234",
512
voice_url="http://example.com/voice",
513
sms_url="http://example.com/sms"
514
)
515
print(f"Purchased: {phone_number.phone_number}")
516
517
# Purchase first available number with area code
518
available = client.available_phone_numbers("US").local.list(
519
area_code="213",
520
limit=1
521
)[0]
522
523
phone_number = client.incoming_phone_numbers.create(
524
phone_number=available.phone_number,
525
friendly_name="My Business Line"
526
)
527
528
# Configure existing number
529
client.incoming_phone_numbers.get("PNxxxxx").update(
530
voice_url="http://newurl.com/voice",
531
voice_method="POST",
532
sms_url="http://newurl.com/sms"
533
)
534
535
# List purchased numbers
536
for number in client.incoming_phone_numbers.list():
537
print(f"{number.friendly_name}: {number.phone_number}")
538
539
# Search toll-free numbers
540
toll_free = client.available_phone_numbers("US").toll_free.list(
541
contains="800",
542
limit=5
543
)
544
```
545
546
### Conference Calls
547
548
Manage conference calls allowing multiple participants to join voice conversations.
549
550
```python { .api }
551
class ConferenceInstance:
552
"""Represents a conference call"""
553
sid: str # Conference SID
554
account_sid: str # Account SID
555
friendly_name: str # Conference name
556
status: str # Conference status
557
date_created: datetime # Creation time
558
date_updated: datetime # Last update
559
participants_count: int # Number of participants
560
max_participants: int # Maximum participants
561
record: bool # Recording enabled
562
uri: str # API resource URI
563
564
class ConferenceList:
565
def list(
566
self,
567
date_created_before: date = None,
568
date_created: date = None,
569
date_created_after: date = None,
570
date_updated_before: date = None,
571
date_updated: date = None,
572
date_updated_after: date = None,
573
friendly_name: str = None,
574
status: str = None,
575
limit: int = None,
576
page_size: int = None
577
) -> Iterator[ConferenceInstance]:
578
"""List conferences with optional filtering"""
579
580
class ParticipantInstance:
581
"""Conference participant"""
582
call_sid: str # Participant's call SID
583
conference_sid: str # Conference SID
584
account_sid: str # Account SID
585
muted: bool # Is participant muted
586
hold: bool # Is participant on hold
587
start_conference_on_enter: bool # Start conference when joining
588
end_conference_on_exit: bool # End conference when leaving
589
coaching: bool # Is in coaching mode
590
call_sid_to_coach: str # Call being coached
591
date_created: datetime # Join time
592
date_updated: datetime # Last update
593
594
def create(
595
self,
596
from_: str,
597
to: str,
598
beep: str = None,
599
start_conference_on_enter: bool = None,
600
end_conference_on_exit: bool = None,
601
wait_url: str = None,
602
wait_method: str = None,
603
max_participants: int = None,
604
record: str = None,
605
muted: bool = None,
606
call_sid_to_coach: str = None,
607
coaching: bool = None,
608
jitter_buffer_size: str = None,
609
conference_status_callback: str = None,
610
conference_status_callback_method: str = None,
611
conference_status_callback_event: list = None,
612
recording_status_callback: str = None,
613
recording_status_callback_method: str = None,
614
conference_record: str = None,
615
sip_auth_username: str = None,
616
sip_auth_password: str = None,
617
region: str = None,
618
conference_trim: str = None,
619
recording_channels: str = None,
620
recording_status_callback_event: list = None,
621
conference_recording_status_callback: str = None,
622
conference_recording_status_callback_method: str = None,
623
recording_track: str = None,
624
time_limit: int = None,
625
machine_detection: str = None,
626
machine_detection_timeout: int = None,
627
machine_detection_speech_threshold: int = None,
628
machine_detection_speech_end_threshold: int = None,
629
machine_detection_silence_timeout: int = None,
630
amd_status_callback: str = None,
631
amd_status_callback_method: str = None,
632
trim: str = None,
633
caller_id: str = None,
634
call_reason: str = None,
635
call_token: str = None,
636
status_callback: str = None,
637
status_callback_method: str = None,
638
status_callback_event: list = None,
639
timeout: int = None,
640
byoc: str = None,
641
early_media: bool = None
642
) -> ParticipantInstance:
643
"""Add a participant to the conference"""
644
645
def update(
646
self,
647
muted: bool = None,
648
hold: bool = None,
649
hold_url: str = None,
650
hold_method: str = None,
651
announce_url: str = None,
652
announce_method: str = None,
653
wait_url: str = None,
654
wait_method: str = None,
655
beep_on_customer_entrance: bool = None,
656
end_conference_on_customer_exit: bool = None,
657
coaching: bool = None,
658
call_sid_to_coach: str = None
659
) -> ParticipantInstance:
660
"""Update participant settings"""
661
```
662
663
Conference call examples:
664
665
```python
666
# List active conferences
667
for conference in client.conferences.list(status="in-progress"):
668
print(f"Conference: {conference.friendly_name} ({conference.participants_count} participants)")
669
670
# Get specific conference
671
conference = client.conferences.get("CFxxxxx").fetch()
672
print(f"Conference status: {conference.status}")
673
674
# List participants in conference
675
participants = client.conferences.get("CFxxxxx").participants.list()
676
for participant in participants:
677
print(f"Participant: {participant.call_sid} (muted: {participant.muted})")
678
679
# Mute participant
680
client.conferences.get("CFxxxxx").participants.get("CAxxxxx").update(muted=True)
681
682
# Remove participant from conference
683
client.conferences.get("CFxxxxx").participants.get("CAxxxxx").delete()
684
685
# Conference participants are typically added via TwiML <Dial><Conference> during call
686
```
687
688
### Call Recording Management
689
690
Manage call recordings including playback URLs, transcriptions, and deletion.
691
692
```python { .api }
693
class RecordingInstance:
694
"""Represents a call recording"""
695
sid: str # Recording SID
696
account_sid: str # Account SID
697
call_sid: str # Associated call SID
698
conference_sid: str # Associated conference SID (if any)
699
status: str # Recording status
700
date_created: datetime # Recording creation time
701
date_updated: datetime # Last update
702
start_time: datetime # Recording start time
703
duration: int # Duration in seconds
704
channels: int # Number of audio channels
705
source: str # Recording source
706
error_code: int # Error code if failed
707
price: str # Cost of recording
708
price_unit: str # Price currency
709
uri: str # API resource URI
710
encryption_details: dict # Encryption information
711
712
class RecordingList:
713
def list(
714
self,
715
date_created_before: date = None,
716
date_created: date = None,
717
date_created_after: date = None,
718
call_sid: str = None,
719
conference_sid: str = None,
720
include_soft_deleted: bool = None,
721
limit: int = None,
722
page_size: int = None
723
) -> Iterator[RecordingInstance]:
724
"""List recordings with optional filtering"""
725
726
def delete(self) -> bool:
727
"""Delete the recording (returns True if successful)"""
728
729
def fetch(self) -> RecordingInstance:
730
"""Fetch current recording details"""
731
```
732
733
Recording management examples:
734
735
```python
736
# List recent recordings
737
for recording in client.recordings.list(limit=20):
738
print(f"Recording {recording.sid}: {recording.duration}s from call {recording.call_sid}")
739
740
# Get specific recording
741
recording = client.recordings.get("RExxxxx").fetch()
742
print(f"Recording status: {recording.status}")
743
print(f"Duration: {recording.duration} seconds")
744
print(f"Recording URL: https://api.twilio.com/2010-04-01/Accounts/{recording.account_sid}/Recordings/{recording.sid}")
745
746
# List recordings for specific call
747
call_recordings = client.recordings.list(call_sid="CAxxxxx")
748
for recording in call_recordings:
749
print(f"Call recording: {recording.sid}")
750
751
# Delete old recordings
752
from datetime import datetime, timedelta
753
cutoff_date = datetime.now() - timedelta(days=30)
754
755
old_recordings = client.recordings.list(date_created_before=cutoff_date)
756
for recording in old_recordings:
757
client.recordings.get(recording.sid).delete()
758
print(f"Deleted recording {recording.sid}")
759
```