Skip to content

Commit 9f2cd1e

Browse files
author
marcel corso gonzalez
authored
Merge pull request #34 from sarathsp06/master
add support for create MMS
2 parents fb7864f + 0785056 commit 9f2cd1e

File tree

7 files changed

+147
-8
lines changed

7 files changed

+147
-8
lines changed

.travis.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ python:
99
install:
1010
- pip install mock==2.0
1111
- pip install requests
12+
- pip install .
1213
script:
1314
- python -m unittest discover -s tests/ -p test_*.py -v
1415
matrix:

examples/mms.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env python
2+
3+
import sys, os
4+
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
5+
6+
import messagebird
7+
8+
ACCESS_KEY = os.environ.get('ACCESS_KEY', None)
9+
if ACCESS_KEY is None:
10+
print("Set environment ACCESS_KEY from https://dashboard.messagebird.com/en/developers/access")
11+
exit(1)
12+
13+
try:
14+
# Create a MessageBird client with the specified ACCESS_KEY.
15+
client = messagebird.Client(ACCESS_KEY)
16+
# Send a MMS
17+
mms = client.mms_create('Sarath','+4915238456487','Rich test message','https://www.messagebird.com/assets/images/og/messagebird.gif')
18+
# Print the object information.
19+
print("The following information was returned as a MMS object:\n%s" % mms)
20+
21+
except messagebird.client.ErrorException as e:
22+
print('\nAn error occured while requesting to send a MMS:\n')
23+
for error in e.errors:
24+
print(' code : %d' % error.code)
25+
print(' description : %s' % error.description)
26+
print(' parameter : %s\n' % error.parameter)

messagebird/base.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,20 @@
33
class Base(object):
44
def load(self, data):
55
for name, value in list(data.items()):
6-
if hasattr(self, name):
6+
if hasattr(self, name) and not callable(getattr(self,name)):
77
setattr(self, name, value)
88

99
return self
10-
11-
def strip_nanoseconds_from_date(self, value):
10+
11+
@staticmethod
12+
def strip_nanoseconds_from_date(value):
1213
if str(value).find(".") != -1:
1314
return value[:-11] + value[-1:]
1415

1516
return value
1617

17-
def value_to_time(self, value, format='%Y-%m-%dT%H:%M:%S+00:00'):
18-
if value != None:
19-
value = self.strip_nanoseconds_from_date(value)
20-
return datetime.strptime(value, format)
18+
@staticmethod
19+
def value_to_time(value, format='%Y-%m-%dT%H:%M:%S+00:00'):
20+
if value is not None:
21+
value = Base.strip_nanoseconds_from_date(value)
22+
return datetime.strptime(value, format)

messagebird/client.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from messagebird.group import Group, GroupList
88
from messagebird.hlr import HLR
99
from messagebird.message import Message
10+
from messagebird.mms import MMS
1011
from messagebird.voicemessage import VoiceMessage
1112
from messagebird.lookup import Lookup
1213
from messagebird.verify import Verify
@@ -110,6 +111,31 @@ def message_delete(self, id):
110111
"""Delete a message from the dashboard."""
111112
self.request_plain_text('messages/' + str(id), 'DELETE')
112113

114+
def mms_create(self, originator, recipients, body, mediaUrls, subject = None, reference = None, scheduledDatetime = None):
115+
''' Send bulk mms.
116+
117+
Args:
118+
originator(str): name of the originator
119+
recipients(str/list(str)): comma seperated numbers or list of numbers in E164 format
120+
body(str) : text message body
121+
mediaUrl(str) : list of URL's of attachments of the MMS message.
122+
subject(str) : utf-encoded subject
123+
reference(str) : client reference text
124+
scheduledDatetime(str) : scheduled date time in RFC3339 format
125+
Raises:
126+
ErrorException: On api returning errors
127+
128+
Returns:
129+
MMS: On success an MMS instance instantiated with succcess response
130+
'''
131+
if isinstance(recipients,list):
132+
recipients = ','.join(recipients)
133+
if isinstance(mediaUrls,str):
134+
mediaUrls = [mediaUrls]
135+
params = locals()
136+
del(params['self'])
137+
return MMS().load(self.request('mms', 'POST', params))
138+
113139
def voice_message(self, id):
114140
"Retrieve the information of a specific voice message."
115141
return VoiceMessage().load(self.request('voicemessages/' + str(id)))
@@ -250,6 +276,6 @@ def conversation_list_webhooks(self, limit=10, offset=0):
250276
def conversation_read_webhook(self, id):
251277
uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id)
252278
return ConversationWebhook().load(self.request(uri, 'GET', None, CONVERSATION_TYPE))
253-
279+
254280
def _format_query(self, limit, offset):
255281
return 'limit=' + str(limit) + '&offset=' + str(offset)

messagebird/mms.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
from messagebird.base import Base
2+
from messagebird.recipient import Recipient
3+
4+
class MMS(Base):
5+
def __init__(self):
6+
self.id = None
7+
self.href = None
8+
self.direction = None
9+
self.originator = None
10+
self.subject = None
11+
self.body = None
12+
self.mediaUrls = None
13+
self.reference = None
14+
self._scheduledDatetime = None
15+
self._createdDatetime = None
16+
self._recipients = None
17+
18+
@property
19+
def scheduledDatetime(self):
20+
return self._scheduledDatetime
21+
22+
@scheduledDatetime.setter
23+
def scheduledDatetime(self, value):
24+
self._scheduledDatetime = self.value_to_time(value)
25+
26+
@property
27+
def createdDatetime(self):
28+
return self._createdDatetime
29+
30+
@createdDatetime.setter
31+
def createdDatetime(self, value):
32+
self._createdDatetime = self.value_to_time(value)
33+
34+
@property
35+
def recipients(self):
36+
return self._recipients
37+
38+
@recipients.setter
39+
def recipients(self, value):
40+
value['items'] = [Recipient().load(r) for r in value['items']]
41+
self._recipients = value
42+
43+
def __str__(self):
44+
return "\n".join([
45+
"id : %s" % self.id ,
46+
"href : %s" % self.href ,
47+
"direction : %s" % self.direction ,
48+
"originator : %s" % self.originator ,
49+
"subject : %s" % self.subject ,
50+
"body : %s" % self.body ,
51+
"mediaUrls : %s" % ",".join(self.mediaUrls),
52+
"reference : %s" % self.reference ,
53+
"scheduledDatetime : %s" % self.scheduledDatetime ,
54+
"createdDatetime : %s" % self.createdDatetime ,
55+
"recipients : %s" % self.recipients,
56+
])

setup.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from os import path
22
from setuptools import setup
3+
from io import open
34

45
def get_description():
56
working_directory = path.abspath(path.dirname(__file__))

tests/test_mms.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import unittest
2+
from messagebird import Client
3+
4+
try:
5+
from unittest.mock import Mock
6+
except ImportError:
7+
# mock was added to unittest in Python 3.3, but was an external library
8+
# before.
9+
from mock import Mock
10+
11+
12+
class TestMMS(unittest.TestCase):
13+
14+
def test_create_mms(self):
15+
http_client = Mock()
16+
http_client.request.return_value = '{"originator": "test-org", "body": "Rich test message", "direction": "mt", "recipients": {"totalCount": 1, "totalSentCount": 1, "totalDeliveredCount": 0, "totalDeliveryFailedCount": 0, "items": [{"status": "sent", "statusDatetime": "2019-06-04T13:54:48+00:00", "recipient": 4915238456487}]}, "reference": null, "createdDatetime": "2019-06-04T13:54:48+00:00", "href": "https://rest.messagebird.com/mms/0a75f8f82b5d4377bd8fb5b22ac1e8ac", "mediaUrls": ["https://www.messagebird.com/assets/images/og/messagebird.gif"], "scheduledDatetime": null, "id": "0a75f8f82b5d4377bd8fb5b22ac1e8ac", "subject": null}'
17+
18+
params = {"originator": "test-org", "body": "Rich test message","recipients":"+4915238456487","mediaUrls":"https://www.messagebird.com/assets/images/og/messagebird.gif"}
19+
mms = Client('', http_client).mms_create(**params)
20+
21+
params["mediaUrls"] = [params["mediaUrls"]]
22+
params.update({'subject': None, 'reference': None, 'scheduledDatetime': None})
23+
http_client.request.assert_called_once_with('mms', 'POST', params)
24+
25+
self.assertEqual(params["originator"], mms.originator)
26+
self.assertEqual(params["recipients"].strip("+"), str(mms.recipients["items"][0].recipient))
27+
self.assertEqual(1,len(mms.recipients["items"]))

0 commit comments

Comments
 (0)