1# coding=utf-8
2r"""
3This code was generated by
4\ / _    _  _|   _  _
5 | (_)\/(_)(_|\/| |(/_  v1.0.0
6      /       /
7"""
8
9from twilio.base import deserialize
10from twilio.base import serialize
11from twilio.base import values
12from twilio.base.instance_context import InstanceContext
13from twilio.base.instance_resource import InstanceResource
14from twilio.base.list_resource import ListResource
15from twilio.base.page import Page
16from twilio.rest.api.v2010.account.message.feedback import FeedbackList
17from twilio.rest.api.v2010.account.message.media import MediaList
18
19
20class MessageList(ListResource):
21
22    def __init__(self, version, account_sid):
23        """
24        Initialize the MessageList
25
26        :param Version version: Version that contains the resource
27        :param account_sid: The SID of the Account that created the resource
28
29        :returns: twilio.rest.api.v2010.account.message.MessageList
30        :rtype: twilio.rest.api.v2010.account.message.MessageList
31        """
32        super(MessageList, self).__init__(version)
33
34        # Path Solution
35        self._solution = {'account_sid': account_sid, }
36        self._uri = '/Accounts/{account_sid}/Messages.json'.format(**self._solution)
37
38    def create(self, to, status_callback=values.unset, application_sid=values.unset,
39               max_price=values.unset, provide_feedback=values.unset,
40               attempt=values.unset, validity_period=values.unset,
41               force_delivery=values.unset, content_retention=values.unset,
42               address_retention=values.unset, smart_encoded=values.unset,
43               persistent_action=values.unset, send_as_mms=values.unset,
44               from_=values.unset, messaging_service_sid=values.unset,
45               body=values.unset, media_url=values.unset):
46        """
47        Create the MessageInstance
48
49        :param unicode to: The destination phone number
50        :param unicode status_callback: The URL we should call to send status information to your application
51        :param unicode application_sid: The application to use for callbacks
52        :param unicode max_price: The total maximum price up to 4 decimal places in US dollars acceptable for the message to be delivered.
53        :param bool provide_feedback: Whether to confirm delivery of the message
54        :param unicode attempt: Total numer of attempts made , this inclusive to send out the message
55        :param unicode validity_period: The number of seconds that the message can remain in our outgoing queue.
56        :param bool force_delivery: Reserved
57        :param MessageInstance.ContentRetention content_retention: Determines if the message content can be stored or redacted based on privacy settings
58        :param MessageInstance.AddressRetention address_retention: Determines if the address can be stored or obfuscated based on privacy settings
59        :param bool smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them
60        :param list[unicode] persistent_action: Rich actions for Channels Messages.
61        :param bool send_as_mms: If set to True, Twilio will deliver the message as a single MMS message, regardless of the presence of media
62        :param unicode from_: The phone number that initiated the message
63        :param unicode messaging_service_sid: The SID of the Messaging Service you want to associate with the message.
64        :param unicode body: The text of the message you want to send. Can be up to 1,600 characters in length.
65        :param list[unicode] media_url: The URL of the media to send with the message
66
67        :returns: The created MessageInstance
68        :rtype: twilio.rest.api.v2010.account.message.MessageInstance
69        """
70        data = values.of({
71            'To': to,
72            'From': from_,
73            'MessagingServiceSid': messaging_service_sid,
74            'Body': body,
75            'MediaUrl': serialize.map(media_url, lambda e: e),
76            'StatusCallback': status_callback,
77            'ApplicationSid': application_sid,
78            'MaxPrice': max_price,
79            'ProvideFeedback': provide_feedback,
80            'Attempt': attempt,
81            'ValidityPeriod': validity_period,
82            'ForceDelivery': force_delivery,
83            'ContentRetention': content_retention,
84            'AddressRetention': address_retention,
85            'SmartEncoded': smart_encoded,
86            'PersistentAction': serialize.map(persistent_action, lambda e: e),
87            'SendAsMms': send_as_mms,
88        })
89
90        payload = self._version.create(method='POST', uri=self._uri, data=data, )
91
92        return MessageInstance(self._version, payload, account_sid=self._solution['account_sid'], )
93
94    def stream(self, to=values.unset, from_=values.unset,
95               date_sent_before=values.unset, date_sent=values.unset,
96               date_sent_after=values.unset, limit=None, page_size=None):
97        """
98        Streams MessageInstance records from the API as a generator stream.
99        This operation lazily loads records as efficiently as possible until the limit
100        is reached.
101        The results are returned as a generator, so this operation is memory efficient.
102
103        :param unicode to: Filter by messages sent to this number
104        :param unicode from_: Filter by from number
105        :param datetime date_sent_before: Filter by date sent
106        :param datetime date_sent: Filter by date sent
107        :param datetime date_sent_after: Filter by date sent
108        :param int limit: Upper limit for the number of records to return. stream()
109                          guarantees to never return more than limit.  Default is no limit
110        :param int page_size: Number of records to fetch per request, when not set will use
111                              the default value of 50 records.  If no page_size is defined
112                              but a limit is defined, stream() will attempt to read the
113                              limit with the most efficient page size, i.e. min(limit, 1000)
114
115        :returns: Generator that will yield up to limit results
116        :rtype: list[twilio.rest.api.v2010.account.message.MessageInstance]
117        """
118        limits = self._version.read_limits(limit, page_size)
119
120        page = self.page(
121            to=to,
122            from_=from_,
123            date_sent_before=date_sent_before,
124            date_sent=date_sent,
125            date_sent_after=date_sent_after,
126            page_size=limits['page_size'],
127        )
128
129        return self._version.stream(page, limits['limit'])
130
131    def list(self, to=values.unset, from_=values.unset,
132             date_sent_before=values.unset, date_sent=values.unset,
133             date_sent_after=values.unset, limit=None, page_size=None):
134        """
135        Lists MessageInstance records from the API as a list.
136        Unlike stream(), this operation is eager and will load `limit` records into
137        memory before returning.
138
139        :param unicode to: Filter by messages sent to this number
140        :param unicode from_: Filter by from number
141        :param datetime date_sent_before: Filter by date sent
142        :param datetime date_sent: Filter by date sent
143        :param datetime date_sent_after: Filter by date sent
144        :param int limit: Upper limit for the number of records to return. list() guarantees
145                          never to return more than limit.  Default is no limit
146        :param int page_size: Number of records to fetch per request, when not set will use
147                              the default value of 50 records.  If no page_size is defined
148                              but a limit is defined, list() will attempt to read the limit
149                              with the most efficient page size, i.e. min(limit, 1000)
150
151        :returns: Generator that will yield up to limit results
152        :rtype: list[twilio.rest.api.v2010.account.message.MessageInstance]
153        """
154        return list(self.stream(
155            to=to,
156            from_=from_,
157            date_sent_before=date_sent_before,
158            date_sent=date_sent,
159            date_sent_after=date_sent_after,
160            limit=limit,
161            page_size=page_size,
162        ))
163
164    def page(self, to=values.unset, from_=values.unset,
165             date_sent_before=values.unset, date_sent=values.unset,
166             date_sent_after=values.unset, page_token=values.unset,
167             page_number=values.unset, page_size=values.unset):
168        """
169        Retrieve a single page of MessageInstance records from the API.
170        Request is executed immediately
171
172        :param unicode to: Filter by messages sent to this number
173        :param unicode from_: Filter by from number
174        :param datetime date_sent_before: Filter by date sent
175        :param datetime date_sent: Filter by date sent
176        :param datetime date_sent_after: Filter by date sent
177        :param str page_token: PageToken provided by the API
178        :param int page_number: Page Number, this value is simply for client state
179        :param int page_size: Number of records to return, defaults to 50
180
181        :returns: Page of MessageInstance
182        :rtype: twilio.rest.api.v2010.account.message.MessagePage
183        """
184        data = values.of({
185            'To': to,
186            'From': from_,
187            'DateSent<': serialize.iso8601_datetime(date_sent_before),
188            'DateSent': serialize.iso8601_datetime(date_sent),
189            'DateSent>': serialize.iso8601_datetime(date_sent_after),
190            'PageToken': page_token,
191            'Page': page_number,
192            'PageSize': page_size,
193        })
194
195        response = self._version.page(method='GET', uri=self._uri, params=data, )
196
197        return MessagePage(self._version, response, self._solution)
198
199    def get_page(self, target_url):
200        """
201        Retrieve a specific page of MessageInstance records from the API.
202        Request is executed immediately
203
204        :param str target_url: API-generated URL for the requested results page
205
206        :returns: Page of MessageInstance
207        :rtype: twilio.rest.api.v2010.account.message.MessagePage
208        """
209        response = self._version.domain.twilio.request(
210            'GET',
211            target_url,
212        )
213
214        return MessagePage(self._version, response, self._solution)
215
216    def get(self, sid):
217        """
218        Constructs a MessageContext
219
220        :param sid: The unique string that identifies the resource
221
222        :returns: twilio.rest.api.v2010.account.message.MessageContext
223        :rtype: twilio.rest.api.v2010.account.message.MessageContext
224        """
225        return MessageContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )
226
227    def __call__(self, sid):
228        """
229        Constructs a MessageContext
230
231        :param sid: The unique string that identifies the resource
232
233        :returns: twilio.rest.api.v2010.account.message.MessageContext
234        :rtype: twilio.rest.api.v2010.account.message.MessageContext
235        """
236        return MessageContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )
237
238    def __repr__(self):
239        """
240        Provide a friendly representation
241
242        :returns: Machine friendly representation
243        :rtype: str
244        """
245        return '<Twilio.Api.V2010.MessageList>'
246
247
248class MessagePage(Page):
249
250    def __init__(self, version, response, solution):
251        """
252        Initialize the MessagePage
253
254        :param Version version: Version that contains the resource
255        :param Response response: Response from the API
256        :param account_sid: The SID of the Account that created the resource
257
258        :returns: twilio.rest.api.v2010.account.message.MessagePage
259        :rtype: twilio.rest.api.v2010.account.message.MessagePage
260        """
261        super(MessagePage, self).__init__(version, response)
262
263        # Path Solution
264        self._solution = solution
265
266    def get_instance(self, payload):
267        """
268        Build an instance of MessageInstance
269
270        :param dict payload: Payload response from the API
271
272        :returns: twilio.rest.api.v2010.account.message.MessageInstance
273        :rtype: twilio.rest.api.v2010.account.message.MessageInstance
274        """
275        return MessageInstance(self._version, payload, account_sid=self._solution['account_sid'], )
276
277    def __repr__(self):
278        """
279        Provide a friendly representation
280
281        :returns: Machine friendly representation
282        :rtype: str
283        """
284        return '<Twilio.Api.V2010.MessagePage>'
285
286
287class MessageContext(InstanceContext):
288
289    def __init__(self, version, account_sid, sid):
290        """
291        Initialize the MessageContext
292
293        :param Version version: Version that contains the resource
294        :param account_sid: The SID of the Account that created the resource to fetch
295        :param sid: The unique string that identifies the resource
296
297        :returns: twilio.rest.api.v2010.account.message.MessageContext
298        :rtype: twilio.rest.api.v2010.account.message.MessageContext
299        """
300        super(MessageContext, self).__init__(version)
301
302        # Path Solution
303        self._solution = {'account_sid': account_sid, 'sid': sid, }
304        self._uri = '/Accounts/{account_sid}/Messages/{sid}.json'.format(**self._solution)
305
306        # Dependents
307        self._media = None
308        self._feedback = None
309
310    def delete(self):
311        """
312        Deletes the MessageInstance
313
314        :returns: True if delete succeeds, False otherwise
315        :rtype: bool
316        """
317        return self._version.delete(method='DELETE', uri=self._uri, )
318
319    def fetch(self):
320        """
321        Fetch the MessageInstance
322
323        :returns: The fetched MessageInstance
324        :rtype: twilio.rest.api.v2010.account.message.MessageInstance
325        """
326        payload = self._version.fetch(method='GET', uri=self._uri, )
327
328        return MessageInstance(
329            self._version,
330            payload,
331            account_sid=self._solution['account_sid'],
332            sid=self._solution['sid'],
333        )
334
335    def update(self, body=values.unset):
336        """
337        Update the MessageInstance
338
339        :param unicode body: The text of the message you want to send
340
341        :returns: The updated MessageInstance
342        :rtype: twilio.rest.api.v2010.account.message.MessageInstance
343        """
344        data = values.of({'Body': body, })
345
346        payload = self._version.update(method='POST', uri=self._uri, data=data, )
347
348        return MessageInstance(
349            self._version,
350            payload,
351            account_sid=self._solution['account_sid'],
352            sid=self._solution['sid'],
353        )
354
355    @property
356    def media(self):
357        """
358        Access the media
359
360        :returns: twilio.rest.api.v2010.account.message.media.MediaList
361        :rtype: twilio.rest.api.v2010.account.message.media.MediaList
362        """
363        if self._media is None:
364            self._media = MediaList(
365                self._version,
366                account_sid=self._solution['account_sid'],
367                message_sid=self._solution['sid'],
368            )
369        return self._media
370
371    @property
372    def feedback(self):
373        """
374        Access the feedback
375
376        :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackList
377        :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackList
378        """
379        if self._feedback is None:
380            self._feedback = FeedbackList(
381                self._version,
382                account_sid=self._solution['account_sid'],
383                message_sid=self._solution['sid'],
384            )
385        return self._feedback
386
387    def __repr__(self):
388        """
389        Provide a friendly representation
390
391        :returns: Machine friendly representation
392        :rtype: str
393        """
394        context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
395        return '<Twilio.Api.V2010.MessageContext {}>'.format(context)
396
397
398class MessageInstance(InstanceResource):
399
400    class Status(object):
401        QUEUED = "queued"
402        SENDING = "sending"
403        SENT = "sent"
404        FAILED = "failed"
405        DELIVERED = "delivered"
406        UNDELIVERED = "undelivered"
407        RECEIVING = "receiving"
408        RECEIVED = "received"
409        ACCEPTED = "accepted"
410        SCHEDULED = "scheduled"
411        READ = "read"
412        PARTIALLY_DELIVERED = "partially_delivered"
413        CANCELED = "canceled"
414
415    class UpdateStatus(object):
416        CANCELED = "canceled"
417
418    class Direction(object):
419        INBOUND = "inbound"
420        OUTBOUND_API = "outbound-api"
421        OUTBOUND_CALL = "outbound-call"
422        OUTBOUND_REPLY = "outbound-reply"
423
424    class ContentRetention(object):
425        RETAIN = "retain"
426
427    class AddressRetention(object):
428        RETAIN = "retain"
429
430    class TrafficType(object):
431        FREE = "free"
432
433    class ScheduleType(object):
434        FIXED = "fixed"
435        OPTIMIZE = "optimize"
436
437    def __init__(self, version, payload, account_sid, sid=None):
438        """
439        Initialize the MessageInstance
440
441        :returns: twilio.rest.api.v2010.account.message.MessageInstance
442        :rtype: twilio.rest.api.v2010.account.message.MessageInstance
443        """
444        super(MessageInstance, self).__init__(version)
445
446        # Marshaled Properties
447        self._properties = {
448            'body': payload.get('body'),
449            'num_segments': payload.get('num_segments'),
450            'direction': payload.get('direction'),
451            'from_': payload.get('from'),
452            'to': payload.get('to'),
453            'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')),
454            'price': payload.get('price'),
455            'error_message': payload.get('error_message'),
456            'uri': payload.get('uri'),
457            'account_sid': payload.get('account_sid'),
458            'num_media': payload.get('num_media'),
459            'status': payload.get('status'),
460            'messaging_service_sid': payload.get('messaging_service_sid'),
461            'sid': payload.get('sid'),
462            'date_sent': deserialize.rfc2822_datetime(payload.get('date_sent')),
463            'date_created': deserialize.rfc2822_datetime(payload.get('date_created')),
464            'error_code': deserialize.integer(payload.get('error_code')),
465            'price_unit': payload.get('price_unit'),
466            'api_version': payload.get('api_version'),
467            'subresource_uris': payload.get('subresource_uris'),
468        }
469
470        # Context
471        self._context = None
472        self._solution = {'account_sid': account_sid, 'sid': sid or self._properties['sid'], }
473
474    @property
475    def _proxy(self):
476        """
477        Generate an instance context for the instance, the context is capable of
478        performing various actions.  All instance actions are proxied to the context
479
480        :returns: MessageContext for this MessageInstance
481        :rtype: twilio.rest.api.v2010.account.message.MessageContext
482        """
483        if self._context is None:
484            self._context = MessageContext(
485                self._version,
486                account_sid=self._solution['account_sid'],
487                sid=self._solution['sid'],
488            )
489        return self._context
490
491    @property
492    def body(self):
493        """
494        :returns: The message text
495        :rtype: unicode
496        """
497        return self._properties['body']
498
499    @property
500    def num_segments(self):
501        """
502        :returns: The number of messages used to deliver the message body
503        :rtype: unicode
504        """
505        return self._properties['num_segments']
506
507    @property
508    def direction(self):
509        """
510        :returns: The direction of the message
511        :rtype: MessageInstance.Direction
512        """
513        return self._properties['direction']
514
515    @property
516    def from_(self):
517        """
518        :returns: The phone number that initiated the message
519        :rtype: unicode
520        """
521        return self._properties['from_']
522
523    @property
524    def to(self):
525        """
526        :returns: The phone number that received the message
527        :rtype: unicode
528        """
529        return self._properties['to']
530
531    @property
532    def date_updated(self):
533        """
534        :returns: The RFC 2822 date and time in GMT that the resource was last updated
535        :rtype: datetime
536        """
537        return self._properties['date_updated']
538
539    @property
540    def price(self):
541        """
542        :returns: The amount billed for the message
543        :rtype: unicode
544        """
545        return self._properties['price']
546
547    @property
548    def error_message(self):
549        """
550        :returns: The description of the error_code
551        :rtype: unicode
552        """
553        return self._properties['error_message']
554
555    @property
556    def uri(self):
557        """
558        :returns: The URI of the resource, relative to `https://api.twilio.com`
559        :rtype: unicode
560        """
561        return self._properties['uri']
562
563    @property
564    def account_sid(self):
565        """
566        :returns: The SID of the Account that created the resource
567        :rtype: unicode
568        """
569        return self._properties['account_sid']
570
571    @property
572    def num_media(self):
573        """
574        :returns: The number of media files associated with the message
575        :rtype: unicode
576        """
577        return self._properties['num_media']
578
579    @property
580    def status(self):
581        """
582        :returns: The status of the message
583        :rtype: MessageInstance.Status
584        """
585        return self._properties['status']
586
587    @property
588    def messaging_service_sid(self):
589        """
590        :returns: The SID of the Messaging Service used with the message.
591        :rtype: unicode
592        """
593        return self._properties['messaging_service_sid']
594
595    @property
596    def sid(self):
597        """
598        :returns: The unique string that identifies the resource
599        :rtype: unicode
600        """
601        return self._properties['sid']
602
603    @property
604    def date_sent(self):
605        """
606        :returns: The RFC 2822 date and time in GMT when the message was sent
607        :rtype: datetime
608        """
609        return self._properties['date_sent']
610
611    @property
612    def date_created(self):
613        """
614        :returns: The RFC 2822 date and time in GMT that the resource was created
615        :rtype: datetime
616        """
617        return self._properties['date_created']
618
619    @property
620    def error_code(self):
621        """
622        :returns: The error code associated with the message
623        :rtype: unicode
624        """
625        return self._properties['error_code']
626
627    @property
628    def price_unit(self):
629        """
630        :returns: The currency in which price is measured
631        :rtype: unicode
632        """
633        return self._properties['price_unit']
634
635    @property
636    def api_version(self):
637        """
638        :returns: The API version used to process the message
639        :rtype: unicode
640        """
641        return self._properties['api_version']
642
643    @property
644    def subresource_uris(self):
645        """
646        :returns: A list of related resources identified by their relative URIs
647        :rtype: unicode
648        """
649        return self._properties['subresource_uris']
650
651    def delete(self):
652        """
653        Deletes the MessageInstance
654
655        :returns: True if delete succeeds, False otherwise
656        :rtype: bool
657        """
658        return self._proxy.delete()
659
660    def fetch(self):
661        """
662        Fetch the MessageInstance
663
664        :returns: The fetched MessageInstance
665        :rtype: twilio.rest.api.v2010.account.message.MessageInstance
666        """
667        return self._proxy.fetch()
668
669    def update(self, body=values.unset):
670        """
671        Update the MessageInstance
672
673        :param unicode body: The text of the message you want to send
674
675        :returns: The updated MessageInstance
676        :rtype: twilio.rest.api.v2010.account.message.MessageInstance
677        """
678        return self._proxy.update(body=body, )
679
680    @property
681    def media(self):
682        """
683        Access the media
684
685        :returns: twilio.rest.api.v2010.account.message.media.MediaList
686        :rtype: twilio.rest.api.v2010.account.message.media.MediaList
687        """
688        return self._proxy.media
689
690    @property
691    def feedback(self):
692        """
693        Access the feedback
694
695        :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackList
696        :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackList
697        """
698        return self._proxy.feedback
699
700    def __repr__(self):
701        """
702        Provide a friendly representation
703
704        :returns: Machine friendly representation
705        :rtype: str
706        """
707        context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
708        return '<Twilio.Api.V2010.MessageInstance {}>'.format(context)
709