chub-dev 0.2.0-beta.1 → 0.2.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,469 @@
1
+ ---
2
+ name: sdk
3
+ description: "Cloud communications platform for SMS, voice, video, and WhatsApp messaging with programmable APIs"
4
+ metadata:
5
+ languages: "python"
6
+ versions: "9.8.4"
7
+ updated-on: "2025-09-25"
8
+ source: maintainer
9
+ tags: "twilio,sdk,sms,voice,communications"
10
+ ---
11
+ # Twilio Python Library Coding Guidelines
12
+
13
+ You are a Twilio Python SDK expert. Help me with writing code using the Twilio Python library to interact with Twilio's communication APIs.
14
+
15
+ Please follow the following guidelines when generating code.
16
+
17
+ You can find the official SDK documentation and code samples here:
18
+ https://www.twilio.com/docs/libraries/python
19
+
20
+ ## Golden Rule: Use the Correct and Current SDK
21
+
22
+ Always use the official Twilio Python library to interact with Twilio APIs, which is the standard and actively maintained library for all Twilio API interactions.
23
+
24
+ - **Library Name:** Twilio Python Helper Library
25
+ - **Python Package:** `twilio`
26
+ - **Current Version:** 9.6.0+
27
+
28
+ **Installation:**
29
+
30
+ - **Correct:** `pip3 install twilio`
31
+ - **Incorrect:** `pip install twilio-sdk` or other unofficial packages
32
+
33
+ **APIs and Usage:**
34
+
35
+ - **Correct:** `from twilio.rest import Client`
36
+ - **Incorrect:** `import twilio` (doesn't expose the Client directly)
37
+ - **Correct:** `client = Client(account_sid, auth_token)`
38
+ - **Correct:** `client.messages.create(...)`
39
+ - **Correct:** `from twilio.base.exceptions import TwilioRestException`
40
+
41
+ ## Supported Python Versions
42
+
43
+ The library supports the following Python versions:
44
+
45
+ - Python 3.7
46
+ - Python 3.8
47
+ - Python 3.9
48
+ - Python 3.10
49
+ - Python 3.11
50
+
51
+ ## Installation and Setup
52
+
53
+ Install using pip:
54
+
55
+ ```bash
56
+ pip3 install twilio
57
+ ```
58
+
59
+ For development, you can also install from source:
60
+
61
+ ```bash
62
+ python3 setup.py install
63
+ ```
64
+
65
+ ## Initialization and Authentication
66
+
67
+ The Twilio client supports multiple authentication methods:
68
+
69
+ ### Account SID and Auth Token Authentication
70
+
71
+ ```python
72
+ from twilio.rest import Client
73
+
74
+ account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
75
+ auth_token = "your_auth_token"
76
+ client = Client(account_sid, auth_token)
77
+ ```
78
+
79
+ ### API Key and Secret Authentication
80
+
81
+ ```python
82
+ from twilio.rest import Client
83
+
84
+ api_key = "XXXXXXXXXXXXXXXXX"
85
+ api_secret = "YYYYYYYYYYYYYYYYYY"
86
+ account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
87
+ client = Client(api_key, api_secret, account_sid)
88
+ ```
89
+
90
+ ### Environment Variables
91
+
92
+ Use environment variables for security:
93
+
94
+ ```python
95
+ from twilio.rest import Client
96
+ # Looks for TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN
97
+ client = Client()
98
+ ```
99
+
100
+ ### Regional Configuration
101
+
102
+ For global infrastructure, specify region and edge:
103
+
104
+ ```python
105
+ from twilio.rest import Client
106
+
107
+ client = Client(region='au1', edge='sydney')
108
+ # Or set after initialization
109
+ client.region = 'au1'
110
+ client.edge = 'sydney'
111
+ ```
112
+
113
+ ## Core Messaging Features
114
+
115
+ ### Send SMS Messages
116
+
117
+ ```python
118
+ from twilio.rest import Client
119
+
120
+ client = Client(account_sid, auth_token)
121
+
122
+ message = client.messages.create(
123
+ to="+15558675309",
124
+ from_="+15017250604",
125
+ body="Hello from Python!"
126
+ )
127
+
128
+ print(message.sid)
129
+ ```
130
+
131
+ ### Send MMS with Media
132
+
133
+ ```python
134
+ message = client.messages.create(
135
+ to="+15558675309",
136
+ from_="+15017250604",
137
+ body="Check out this image!",
138
+ media_url=["https://example.com/image.jpg"]
139
+ )
140
+ ```
141
+
142
+ ### Retrieve Message Information
143
+
144
+ ```python
145
+ # Get specific message
146
+ message = client.messages.get("MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
147
+ print(f"Status: {message.status}")
148
+ print(f"Direction: {message.direction}")
149
+ print(f"Error Code: {message.error_code}")
150
+ ```
151
+
152
+ ## Voice Features
153
+
154
+ ### Make Phone Calls
155
+
156
+ ```python
157
+ from twilio.rest import Client
158
+
159
+ client = Client(account_sid, auth_token)
160
+
161
+ call = client.calls.create(
162
+ to="+15558675309",
163
+ from_="+15017250604",
164
+ url="http://demo.twilio.com/docs/voice.xml"
165
+ )
166
+
167
+ print(call.sid)
168
+ ```
169
+
170
+ ### Get Call Information
171
+
172
+ ```python
173
+ call = client.calls.get("CA42ed11f93dc08b952027ffbc406d0868")
174
+ print(f"Duration: {call.duration}")
175
+ print(f"Status: {call.status}")
176
+ ```
177
+
178
+ ## Data Iteration and Pagination
179
+
180
+ The library handles pagination automatically:
181
+
182
+ ### Using List Method
183
+
184
+ ```python
185
+ # Get all messages (automatically handles pagination)
186
+ for message in client.messages.list():
187
+ print(f"To: {message.to}, Body: {message.body}")
188
+
189
+ # With limits and page size
190
+ messages = client.messages.list(limit=20, page_size=10)
191
+ ```
192
+
193
+ ### Using Stream Method
194
+
195
+ ```python
196
+ # Lazy loading with iterator
197
+ for message in client.messages.stream(limit=100):
198
+ print(message.sid)
199
+ ```
200
+
201
+ ## TwiML Generation
202
+
203
+ Generate TwiML responses for webhooks:
204
+
205
+ ### Voice TwiML
206
+
207
+ ```python
208
+ from twilio.twiml.voice_response import VoiceResponse
209
+
210
+ response = VoiceResponse()
211
+ response.say("Hello! Welcome to our service.")
212
+ response.play("https://api.twilio.com/cowbell.mp3")
213
+
214
+ # For call forwarding
215
+ response.dial("+15551234567")
216
+
217
+ print(str(response))
218
+ ```
219
+
220
+ ### Messaging TwiML
221
+
222
+ ```python
223
+ from twilio.twiml.messaging_response import MessagingResponse
224
+
225
+ response = MessagingResponse()
226
+ response.message("Thanks for your message! We'll get back to you soon.")
227
+
228
+ print(str(response))
229
+ ```
230
+
231
+ ### Advanced Voice TwiML
232
+
233
+ ```python
234
+ from twilio.twiml.voice_response import VoiceResponse, Gather
235
+
236
+ response = VoiceResponse()
237
+
238
+ gather = Gather(input='speech dtmf', timeout=3, action='/process-input')
239
+ gather.say("Please say your name or press a key")
240
+ response.append(gather)
241
+
242
+ # Fallback if no input
243
+ response.say("We didn't receive any input. Goodbye!")
244
+ ```
245
+
246
+ ## Asynchronous Operations
247
+
248
+ For non-blocking requests, use async client:
249
+
250
+ ```python
251
+ import asyncio
252
+ from twilio.http.async_http_client import AsyncTwilioHttpClient
253
+ from twilio.rest import Client
254
+
255
+ async def send_message_async():
256
+ account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
257
+ auth_token = "your_auth_token"
258
+
259
+ http_client = AsyncTwilioHttpClient()
260
+ client = Client(account_sid, auth_token, http_client=http_client)
261
+
262
+ message = await client.messages.create_async(
263
+ to="+12316851234",
264
+ from_="+15555555555",
265
+ body="Hello there!"
266
+ )
267
+
268
+ return message.sid
269
+
270
+ # Run the async function
271
+ result = asyncio.run(send_message_async())
272
+ ```
273
+
274
+ ## Error Handling
275
+
276
+ Handle Twilio-specific exceptions:
277
+
278
+ ```python
279
+ from twilio.rest import Client
280
+ from twilio.base.exceptions import TwilioRestException
281
+
282
+ client = Client(account_sid, auth_token)
283
+
284
+ try:
285
+ message = client.messages.create(
286
+ to="+12316851234",
287
+ from_="+15555555555",
288
+ body="Hello there!"
289
+ )
290
+ except TwilioRestException as e:
291
+ print(f"Twilio Error {e.status}: {e.msg}")
292
+ print(f"Error Code: {e.code}")
293
+ print(f"More info: https://www.twilio.com/docs/errors/{e.code}")
294
+ except Exception as e:
295
+ print(f"Other error: {e}")
296
+ ```
297
+
298
+ ## Webhook Validation
299
+
300
+ Validate incoming webhook requests:
301
+
302
+ ```python
303
+ from twilio.request_validator import RequestValidator
304
+
305
+ def validate_twilio_request(request):
306
+ validator = RequestValidator("your_auth_token")
307
+
308
+ # Get the URL and signature from request
309
+ url = request.url
310
+ params = request.form # or request.json for JSON requests
311
+ signature = request.headers.get('X-Twilio-Signature', '')
312
+
313
+ if validator.validate(url, params, signature):
314
+ return True
315
+ else:
316
+ return False
317
+
318
+ # Example with Flask
319
+ from flask import Flask, request
320
+
321
+ app = Flask(__name__)
322
+
323
+ @app.route("/webhook", methods=['POST'])
324
+ def handle_webhook():
325
+ if not validate_twilio_request(request):
326
+ return "Unauthorized", 401
327
+
328
+ # Process the webhook
329
+ return "OK", 200
330
+ ```
331
+
332
+ ## Advanced Features
333
+
334
+ ### Custom HTTP Client
335
+
336
+ Create custom HTTP client for proxy support:
337
+
338
+ ```python
339
+ from twilio.http.http_client import TwilioHttpClient
340
+ from twilio.rest import Client
341
+ import os
342
+
343
+ class ProxyHttpClient(TwilioHttpClient):
344
+ def request(self, method, url, params=None, data=None, headers=None,
345
+ auth=None, timeout=None, allow_redirects=False):
346
+ # Customize the request here
347
+ session = self._build_session()
348
+ session.proxies.update({
349
+ 'http': os.environ.get('HTTP_PROXY'),
350
+ 'https': os.environ.get('HTTPS_PROXY')
351
+ })
352
+
353
+ response = session.request(
354
+ method=method,
355
+ url=url,
356
+ params=params,
357
+ data=data,
358
+ headers=headers,
359
+ auth=auth,
360
+ timeout=timeout,
361
+ allow_redirects=allow_redirects
362
+ )
363
+
364
+ return self._build_response(response)
365
+
366
+ # Use custom client
367
+ custom_client = ProxyHttpClient()
368
+ client = Client(account_sid, auth_token, http_client=custom_client)
369
+ ```
370
+
371
+ ### Debug Logging
372
+
373
+ Enable request/response logging:
374
+
375
+ ```python
376
+ import logging
377
+ from twilio.rest import Client
378
+
379
+ client = Client(account_sid, auth_token)
380
+
381
+ # Log to console
382
+ logging.basicConfig()
383
+ client.http_client.logger.setLevel(logging.INFO)
384
+
385
+ # Log to file
386
+ logging.basicConfig(filename='./twilio_log.txt')
387
+ client.http_client.logger.setLevel(logging.INFO)
388
+ ```
389
+
390
+ ### Advanced Service Access
391
+
392
+ Access specific Twilio services directly:
393
+
394
+ ```python
395
+ # Video API
396
+ rooms = client.video.rooms.list()
397
+
398
+ # Verify API
399
+ verification = client.verify.services("VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
400
+ .verifications.create(to="+15017122661", channel="sms")
401
+
402
+ # Sync API
403
+ sync_service = client.sync.services.create(friendly_name="My Service")
404
+
405
+ # Studio API
406
+ executions = client.studio.flows("FWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
407
+ .executions.list()
408
+ ```
409
+
410
+ ## Best Practices
411
+
412
+ ### Security
413
+ - Always use environment variables for credentials
414
+ - Validate webhook requests
415
+ - Use API keys instead of Auth Tokens when possible
416
+ - Implement proper error handling
417
+
418
+ ### Performance
419
+ - Use pagination limits for large datasets
420
+ - Consider async operations for high-volume applications
421
+ - Implement retry logic for network failures
422
+ - Use connection pooling for multiple requests
423
+
424
+ ### Error Handling
425
+ - Always catch `TwilioRestException` for API errors
426
+ - Check response status codes
427
+ - Log errors with context for debugging
428
+ - Implement graceful fallbacks
429
+
430
+ ### Resource Management
431
+ - Close async clients properly
432
+ - Use context managers when appropriate
433
+ - Monitor API usage and rate limits
434
+ - Cache frequently accessed data
435
+
436
+ ## Available APIs and Services
437
+
438
+ The Twilio Python library provides access to numerous APIs:
439
+
440
+ - **Messaging**: SMS, MMS, WhatsApp, Facebook Messenger
441
+ - **Voice**: Calls, conferences, recordings, transcriptions
442
+ - **Video**: Rooms, participants, compositions
443
+ - **Verify**: Phone verification, TOTP, email verification
444
+ - **Sync**: Real-time synchronization
445
+ - **Chat**: Programmable chat (legacy)
446
+ - **Conversations**: Next-generation chat and messaging
447
+ - **Studio**: Visual workflow builder
448
+ - **Functions**: Serverless runtime
449
+ - **Flex**: Contact center platform
450
+ - **TaskRouter**: Workflow and task distribution
451
+ - **Proxy**: Phone number masking
452
+ - **Notify**: Push notifications and messaging
453
+ - **Authy**: Two-factor authentication (via Verify)
454
+ - **Lookup**: Phone number intelligence
455
+ - **Pricing**: Cost information
456
+ - **Usage**: Account usage statistics
457
+
458
+ ## Useful Links
459
+
460
+ - Documentation: https://www.twilio.com/docs/libraries/python
461
+ - API Reference: https://www.twilio.com/docs/api
462
+ - TwiML Reference: https://www.twilio.com/docs/voice/twiml
463
+ - Console: https://console.twilio.com
464
+ - Status Page: https://status.twilio.com
465
+ - Support: https://support.twilio.com
466
+
467
+ ## Notes
468
+
469
+ The Twilio Python library is auto-generated from OpenAPI specifications, ensuring it stays current with Twilio's APIs. Always refer to the official documentation for the most up-to-date API parameters and responses. The library provides both synchronous and asynchronous interfaces, comprehensive error handling, and extensive webhook validation capabilities for building robust communication applications.