From a38270f547033f4fb3b4cb60572be54ede94df0b Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Tue, 2 Apr 2019 11:59:23 +0200 Subject: [PATCH 01/16] Add conversation start function --- examples/conversation_list_messages.py | 37 ++++++++++++++ examples/conversation_start.py | 62 ++++++++++++++++++++++++ messagebird/__init__.py | 1 + messagebird/base.py | 4 +- messagebird/conversation.py | 66 +++++++++++++++++++++++++ messagebird/conversation_channel.py | 26 ++++++++++ messagebird/conversation_client.py | 67 ++++++++++++++++++++++++++ messagebird/conversation_contact.py | 39 +++++++++++++++ messagebird/conversation_message.py | 41 ++++++++++++++++ messagebird/conversation_webhook.py | 8 +++ tests/test_conversation.py | 35 ++++++++++++++ 11 files changed, 384 insertions(+), 2 deletions(-) create mode 100644 examples/conversation_list_messages.py create mode 100644 examples/conversation_start.py create mode 100644 messagebird/conversation.py create mode 100644 messagebird/conversation_channel.py create mode 100644 messagebird/conversation_client.py create mode 100644 messagebird/conversation_contact.py create mode 100644 messagebird/conversation_message.py create mode 100644 messagebird/conversation_webhook.py create mode 100644 tests/test_conversation.py diff --git a/examples/conversation_list_messages.py b/examples/conversation_list_messages.py new file mode 100644 index 0000000..47aea56 --- /dev/null +++ b/examples/conversation_list_messages.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python + +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + +import messagebird + +# ACCESS_KEY = '' +# MESSAGE_ID = '' + +try: + ACCESS_KEY +except NameError: + print('You need to set an ACCESS_KEY constant in this file') + sys.exit(1) + +try: + CONVERSATION_ID +except NameError: + print('You need to set a CONVERSATION_ID constant in this file') + sys.exit(1) + +try: + client = messagebird.ConversationClient(ACCESS_KEY) + + msg = client.list_messages(CONVERSATION_ID) + + # Print the object information. + print(msg) + +except messagebird.client.ErrorException as e: + print('\nAn error occured while requesting a Message object:\n') + + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/examples/conversation_start.py b/examples/conversation_start.py new file mode 100644 index 0000000..4eb89d1 --- /dev/null +++ b/examples/conversation_start.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python + +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + +import messagebird +from messagebird.conversation_message import MESSAGE_TYPE_TEXT + +# ACCESS_KEY = '' +# CHANNEL_ID = '' +# PHONE_NUMBER = '' +# TEXT_MESSAGE = '' + +try: + ACCESS_KEY +except NameError: + print('You need to set an ACCESS_KEY constant in this file') + sys.exit(1) + +try: + CHANNEL_ID +except NameError: + print('You need to set a CHANNEL_ID constant in this file') + sys.exit(1) + +try: + PHONE_NUMBER +except NameError: + print('You need to set a PHONE_NUMBEr constant in this file') + sys.exit(1) + +try: + TEXT_NUMBER +except NameError: + print('You need to set a TEXT_NUMBER constant in this file') + sys.exit(1) + +try: + client = messagebird.ConversationClient(ACCESS_KEY) + + msg = client.start({ 'channelId': CHANNEL_ID, 'to': PHONE_NUMBER, 'type': MESSAGE_TYPE_TEXT, 'content': { 'text': TEXT_MESSAGE } }) + + # Print the object information. + print('\nThe following information was returned as a Conversation object:\n') + print(' id : %s' % msg.id) + print(' contact id : %s' % msg.contactId) + print(' contact : %s' % msg.contact) + print(' last used channel id : %s' % msg.lastUsedChannelId) + print(' channels : %s' % msg.channels) + print(' messages : %s' % msg.messages) + print(' status : %s' % msg.status) + print(' createdDateTime : %s' % msg.createdDateTime) + print(' updatedDateTime : %s' % msg.updatedDateTime) + print(' lastReceivedDateTime : %s' % msg.lastReceivedDateTime) + +except messagebird.client.ErrorException as e: + print('\nAn error occured while requesting a Message object:\n') + + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/messagebird/__init__.py b/messagebird/__init__.py index cf57a14..94f4461 100644 --- a/messagebird/__init__.py +++ b/messagebird/__init__.py @@ -1 +1,2 @@ from messagebird.client import Client, ErrorException +from messagebird.conversation_client import ConversationClient diff --git a/messagebird/base.py b/messagebird/base.py index 32a1906..7485f02 100644 --- a/messagebird/base.py +++ b/messagebird/base.py @@ -8,6 +8,6 @@ def load(self, data): return self - def value_to_time(self, value): + def value_to_time(self, value, format='%Y-%m-%dT%H:%M:%S+00:00'): if value != None: - return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S+00:00') + return datetime.strptime(value, format) diff --git a/messagebird/conversation.py b/messagebird/conversation.py new file mode 100644 index 0000000..ef5bd23 --- /dev/null +++ b/messagebird/conversation.py @@ -0,0 +1,66 @@ +from messagebird.base import Base +from messagebird.conversation_contact import ConversationContact +from messagebird.conversation_channel import Channel + +CONVERSATION_STATUS_ACTIVE = "active" +CONVERSATION_STATUS_ARCHIVED = "archived" + + +class Conversation(Base): + + def __init__(self): + self.id = None + self.contactId = None + self._contact = None + self.lastUsedChannelId = None + self.channels = None + self.messages = None + self.status = None + self._createdDateTime = None + self._updatedDateTime = None + self._lastReceivedDateTime = None + + @property + def contact(self): + return self._contact + + @contact.setter + def contact(self, value): + self._contact = ConversationContact().load(value) + + @property + def channels(self): + return self._channels + + @channels.setter + def channels(self, value): + if isinstance(value, list): + self._channels = [] + for channelData in value: + self._channels.append(Channel().load(channelData)) + else: + self._channels = value + + @property + def createdDateTime(self): + return self._createdDateTime + + @createdDateTime.setter + def createdDateTime(self, value): + self._createdDateTime = self.value_to_time(value) + + @property + def updatedDateTime(self): + return self._updatedDateTime + + @updatedDateTime.setter + def updatedDateTime(self, value): + self._updatedDateTime = self.value_to_time(value) + + @property + def lastReceivedDateTime(self): + return self._lastReceivedDateTime + + @lastReceivedDateTime.setter + def lastReceivedDateTime(self, value): + self._lastReceivedDateTime = self.value_to_time(value) \ No newline at end of file diff --git a/messagebird/conversation_channel.py b/messagebird/conversation_channel.py new file mode 100644 index 0000000..7f359ca --- /dev/null +++ b/messagebird/conversation_channel.py @@ -0,0 +1,26 @@ +from messagebird.base import Base + +class Channel(Base): + def __init__(self): + self.id = None + self.name = None + self.platformId = None + self.status = None + self._createdDateTime = None + self._updatedDateTime = None + + @property + def createdDateTime(self): + return self._createdDateTime + + @createdDateTime.setter + def createdDateTime(self, value): + self._createdDateTime = self.value_to_time(value) + + @property + def updatedDateTime(self): + return self._updatedDateTime + + @updatedDateTime.setter + def updatedDateTime(self, value): + self._updatedDateTime = self.value_to_time(value) \ No newline at end of file diff --git a/messagebird/conversation_client.py b/messagebird/conversation_client.py new file mode 100644 index 0000000..d9734ca --- /dev/null +++ b/messagebird/conversation_client.py @@ -0,0 +1,67 @@ +from messagebird.base import Base +from messagebird.client import USER_AGENT, Client +from messagebird.http_client import HttpClient +from messagebird.conversation_message import ConversationMessage, ConversationMessageList +from messagebird.conversation import Conversation + +try: + from urllib.parse import urlencode +except ImportError: + from urllib import urlencode + +CONVERSATION_API_ROOT = 'https://conversations.messagebird.com/v1/' +CONVERSATION_PATH = 'conversations' +CONVERSATION_MESSAGES_PATH = 'messages' +CONVERSATION_WEB_HOOKS_PATH = 'webhooks' + + +class ConversationClient(Base): + + def __init__(self, access_key, http_client=None): + self.access_key = access_key + + if http_client is None: + http_client = HttpClient(CONVERSATION_API_ROOT, access_key, USER_AGENT) + + self.client = Client(access_key, http_client) + + def list(self): + return self.access_key + + def start(self, start_request): + uri = CONVERSATION_PATH + '/start' + return Conversation().load(self.client.request(uri, 'POST', start_request)) + + def update(self, id): + return self.access_key + + def read(self, id): + return self.access_key + + def list_messages(self, conversation_id, options=None): + uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH + + if options is None: + uri += '?' + urlencode(options) + + return ConversationMessageList().load(self.client.request(uri)) + + def create_message(self, conversation_id, message_create_request): + uri = str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH + return ConversationMessage().load(self.client.request(uri, 'POST', message_create_request)) + + def read_message(self, message_id): + uri = CONVERSATION_MESSAGES_PATH + '/' + str(message_id) + return ConversationMessage().load(self.client.request(uri)) + + def create_webhook(self): + return self.access_key + + def delete_webhook(self): + return self.access_key + + def list_webhooks(self): + return self.access_key + + def read_webhook(self): + return self.access_key \ No newline at end of file diff --git a/messagebird/conversation_contact.py b/messagebird/conversation_contact.py new file mode 100644 index 0000000..4c58a62 --- /dev/null +++ b/messagebird/conversation_contact.py @@ -0,0 +1,39 @@ +from messagebird.base import Base +from messagebird.contact import CustomDetails + + +class ConversationContact(Base): + + def __init__(self): + self.id = None + self.href = None + self.msisdn = None + self.firstName = None + self.lastName = None + self._customDetails = None + self._createdDatetime = None + self._updatedDatetime = None + + @property + def customDetails(self): + return self._customDetails + + @customDetails.setter + def customDetails(self, value): + self._customDetails = CustomDetails().load(value) + + @property + def createdDatetime(self): + return self._createdDatetime + + @createdDatetime.setter + def createdDatetime(self, value): + self._createdDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') + + @property + def updatedDatetime(self): + return self._updatedDatetime + + @updatedDatetime.setter + def updatedDatetime(self, value): + self._updatedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') \ No newline at end of file diff --git a/messagebird/conversation_message.py b/messagebird/conversation_message.py new file mode 100644 index 0000000..1bb0645 --- /dev/null +++ b/messagebird/conversation_message.py @@ -0,0 +1,41 @@ +from messagebird.base import Base + +MESSAGE_TYPE_AUDIO = "audio" +MESSAGE_TYPE_FILE = "file" +MESSAGE_TYPE_HSM = "hsm" +MESSAGE_TYPE_IMAGE = "image" +MESSAGE_TYPE_LOCATION = "location" +MESSAGE_TYPE_TEXT = "text" +MESSAGE_TYPE_VIDEO = "video" + + +class ConversationMessage(Base): + + def __init__(self): + self.id = None + self.conversationId = None + self.channelId = None + self.direction = None + self.status = None + self.type = None + self.content = None + self.createdDateTime = None + self.updatedDateTime = None + + +class ConversationMessageList(Base): + + def __init__(self): + self.offset = None + self.limit = None + self.count = None + self.totalCount = None + self.items = None + + +class ConversationMessageCreateRequest(Base): + + def __init__(self): + self.channelId = None + self.content = None + self.type = None diff --git a/messagebird/conversation_webhook.py b/messagebird/conversation_webhook.py new file mode 100644 index 0000000..7a3c6c8 --- /dev/null +++ b/messagebird/conversation_webhook.py @@ -0,0 +1,8 @@ +from messagebird.base import Base + +class ConversationWebhookCreateRequest(Base): + + def __init__(self): + self.channelId = None + self.events = None + self.url = None diff --git a/tests/test_conversation.py b/tests/test_conversation.py new file mode 100644 index 0000000..4e7d805 --- /dev/null +++ b/tests/test_conversation.py @@ -0,0 +1,35 @@ +import unittest +from datetime import datetime +from messagebird import ConversationClient + +try: + from unittest.mock import Mock +except ImportError: + # mock was added to unittest in Python 3.3, but was an external library + # before. + from mock import Mock + +class TestConversation(unittest.TestCase): + + def test_conversation_start(self): + http_client = Mock() + http_client.request.return_value = '{"id":"1234","contactId":"1234","contact":{"id":"1234","href":"https://contacts.messagebird.com/v2/contacts/1234","msisdn":99999999999,"displayName":"99999999999","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:19:38Z"},"channels":[{"id":"1234","name":"channel-name","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:54:42.497114599Z","lastReceivedDatetime":"2019-04-02T08:54:42.464955904Z","lastUsedChannelId":"1234","messages":{"totalCount":1,"href":"https://conversations.messagebird.com/v1/conversations/1234/messages"}}' + + data = { + 'channelId': '1234', + 'to': '+99999999999', + 'type': "text", + 'content': { + 'text': 'Message Example' + }, + } + + msg = ConversationClient('', http_client).start(data) + + http_client.request.assert_called_once_with('conversations/start', 'POST', data) + + self.assertEqual('1234', msg.id) + self.assertEqual(99999999999, msg.contact.msisdn) + self.assertEqual(datetime(2019, 4, 2, 8, 19, 37), msg.contact.createdDatetime) + self.assertEqual(datetime(2019, 4, 2, 8, 19, 38), msg.contact.updatedDatetime) + self.assertEqual('channel-name', msg.channels[0].name) \ No newline at end of file From 293e20d979a49221610efe340f42ea6acc7edf6d Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Tue, 2 Apr 2019 13:38:39 +0200 Subject: [PATCH 02/16] Add list messages function --- examples/conversation_list_messages.py | 12 ++++++++++-- messagebird/conversation_client.py | 2 +- messagebird/conversation_message.py | 17 +++++++++++------ tests/test_conversation.py | 1 + tests/test_conversation_message.py | 24 ++++++++++++++++++++++++ 5 files changed, 47 insertions(+), 9 deletions(-) create mode 100644 tests/test_conversation_message.py diff --git a/examples/conversation_list_messages.py b/examples/conversation_list_messages.py index 47aea56..9c87350 100644 --- a/examples/conversation_list_messages.py +++ b/examples/conversation_list_messages.py @@ -6,7 +6,7 @@ import messagebird # ACCESS_KEY = '' -# MESSAGE_ID = '' +# CONVERSATION_ID = '' try: ACCESS_KEY @@ -25,8 +25,16 @@ msg = client.list_messages(CONVERSATION_ID) + itemIds = [] + for msgItem in msg.items: + itemIds.append(msgItem.id) + # Print the object information. - print(msg) + print('\nThe following information was returned as a Conversation List object:\n') + print(' message ids : %s' % itemIds) + print(' offset : %s' % msg.offset) + print(' limit : %s', msg.limit) + print(' totalCount : %s', msg.totalCount) except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a Message object:\n') diff --git a/messagebird/conversation_client.py b/messagebird/conversation_client.py index d9734ca..0dc1ea0 100644 --- a/messagebird/conversation_client.py +++ b/messagebird/conversation_client.py @@ -41,7 +41,7 @@ def read(self, id): def list_messages(self, conversation_id, options=None): uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH - if options is None: + if options is not None: uri += '?' + urlencode(options) return ConversationMessageList().load(self.client.request(uri)) diff --git a/messagebird/conversation_message.py b/messagebird/conversation_message.py index 1bb0645..9800e63 100644 --- a/messagebird/conversation_message.py +++ b/messagebird/conversation_message.py @@ -30,12 +30,17 @@ def __init__(self): self.limit = None self.count = None self.totalCount = None - self.items = None + self._items = None + @property + def items(self): + return self._items -class ConversationMessageCreateRequest(Base): + @items.setter + def items(self, value): + items = [] + if isinstance(value, list): + for item in value: + items.append(ConversationMessage().load(item)) - def __init__(self): - self.channelId = None - self.content = None - self.type = None + self._items = items diff --git a/tests/test_conversation.py b/tests/test_conversation.py index 4e7d805..3721c56 100644 --- a/tests/test_conversation.py +++ b/tests/test_conversation.py @@ -9,6 +9,7 @@ # before. from mock import Mock + class TestConversation(unittest.TestCase): def test_conversation_start(self): diff --git a/tests/test_conversation_message.py b/tests/test_conversation_message.py new file mode 100644 index 0000000..9101ef6 --- /dev/null +++ b/tests/test_conversation_message.py @@ -0,0 +1,24 @@ +import unittest +from datetime import datetime +from messagebird import ConversationClient + +try: + from unittest.mock import Mock +except ImportError: + # mock was added to unittest in Python 3.3, but was an external library + # before. + from mock import Mock + + +class TestConversationMessage(unittest.TestCase): + + def test_conversation_list_messages(self): + http_client = Mock() + http_client.request.return_value = '{"count":1,"items":[{"id":"54445534","conversationId":"54345543543","channelId":"4535434354","type":"text","content":{"text":"Hello"},"direction":"sent","status":"delivered","createdDatetime":"2019-04-02T08:54:54.608157775Z","updatedDatetime":"2019-04-02T08:54:54.63910221Z"}],"limit":10,"offset":0,"totalCount":1}' + + msg = ConversationClient('', http_client).list_messages(54567) + + self.assertEqual(1, msg.count) + self.assertEqual('54445534', msg.items[0].id) + + http_client.request.assert_called_once_with('conversations/54567/messages', 'GET', None) \ No newline at end of file From b9df425d767379d37b04a8b9e9551709c33a9db7 Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Tue, 2 Apr 2019 16:31:58 +0200 Subject: [PATCH 03/16] Add create_message method to conversation client --- examples/conversation_create_message.py | 61 +++++++++++++++++++++++++ examples/conversation_read_message.py | 0 messagebird/conversation_client.py | 2 +- messagebird/conversation_message.py | 27 ++++++++++- tests/test_conversation_message.py | 21 ++++++++- 5 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 examples/conversation_create_message.py create mode 100644 examples/conversation_read_message.py diff --git a/examples/conversation_create_message.py b/examples/conversation_create_message.py new file mode 100644 index 0000000..a473b3b --- /dev/null +++ b/examples/conversation_create_message.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python + +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + +import messagebird +from messagebird.conversation_message import MESSAGE_TYPE_TEXT + +# ACCESS_KEY = '' +# CONVERSATION_ID = '' +# CHANNEL_ID = '' +# TEXT_MESSAGE = '' + +try: + ACCESS_KEY +except NameError: + print('You need to set an ACCESS_KEY constant in this file') + sys.exit(1) + +try: + CONVERSATION_ID +except NameError: + print('You need to set a CONVERSATION_ID constant in this file') + sys.exit(1) + +try: + CHANNEL_ID +except NameError: + print('You need to set a CHANNEL_ID constant in this file') + sys.exit(1) + +try: + TEXT_MESSAGE +except NameError: + print('You need to set a TEXT_MESSAGE constant in this file') + sys.exit(1) + +try: + client = messagebird.ConversationClient(ACCESS_KEY) + + msg = client.create_message(CONVERSATION_ID, { 'channelId': CHANNEL_ID, 'type': MESSAGE_TYPE_TEXT, 'content': { 'text': TEXT_MESSAGE } }) + + # Print the object information. + print('\nThe following information was returned as a Conversation List object:\n') + print(' message id : %s' % msg.id) + print(' channel id : %s' % msg.channelId) + print(' direction : %s' % msg.direction) + print(' content : %s' % msg.content) + print(' content : %s' % msg.content) + print(' status : %s' % msg.status) + print(' type : %s' % msg.type) + print(' created date : %s' % msg.createdDateTime) + print(' updated date : %s' % msg.updatedDateTime) + +except messagebird.client.ErrorException as e: + print('\nAn error occured while requesting a Message object:\n') + + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/examples/conversation_read_message.py b/examples/conversation_read_message.py new file mode 100644 index 0000000..e69de29 diff --git a/messagebird/conversation_client.py b/messagebird/conversation_client.py index 0dc1ea0..bb0143a 100644 --- a/messagebird/conversation_client.py +++ b/messagebird/conversation_client.py @@ -47,7 +47,7 @@ def list_messages(self, conversation_id, options=None): return ConversationMessageList().load(self.client.request(uri)) def create_message(self, conversation_id, message_create_request): - uri = str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH + uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH return ConversationMessage().load(self.client.request(uri, 'POST', message_create_request)) def read_message(self, message_id): diff --git a/messagebird/conversation_message.py b/messagebird/conversation_message.py index 9800e63..e5f04ed 100644 --- a/messagebird/conversation_message.py +++ b/messagebird/conversation_message.py @@ -19,8 +19,31 @@ def __init__(self): self.status = None self.type = None self.content = None - self.createdDateTime = None - self.updatedDateTime = None + self._createdDatetime = None + self._updatedDatetime = None + + @property + def createdDatetime(self): + return self._createdDatetime + + @createdDatetime.setter + def createdDatetime(self, value): + if value is not None: + value = self.strip_nanoseconds_from_date(value) + self._createdDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') + + @property + def updatedDatetime(self): + return self._updatedDatetime + + @updatedDatetime.setter + def updatedDatetime(self, value): + if value is not None: + value = self.strip_nanoseconds_from_date(value) + self._updatedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') + + def strip_nanoseconds_from_date(self, value): + return value[:-11] + value[-1:] class ConversationMessageList(Base): diff --git a/tests/test_conversation_message.py b/tests/test_conversation_message.py index 9101ef6..a97516b 100644 --- a/tests/test_conversation_message.py +++ b/tests/test_conversation_message.py @@ -21,4 +21,23 @@ def test_conversation_list_messages(self): self.assertEqual(1, msg.count) self.assertEqual('54445534', msg.items[0].id) - http_client.request.assert_called_once_with('conversations/54567/messages', 'GET', None) \ No newline at end of file + http_client.request.assert_called_once_with('conversations/54567/messages', 'GET', None) + + def test_create_message(self): + http_client = Mock() + http_client.request.return_value = '{"id":"id","conversationId":"conversation-id","channelId":"channel-id","type":"text","content":{"text":"Example Text Message"},"direction":"sent","status":"pending","createdDatetime":"2019-04-02T11:57:52.142641447Z","updatedDatetime":"2019-04-02T11:57:53.142641447Z"}' + + data = { + 'channelId': 1234, + 'type': 'text', + 'content': { + 'text': 'this is a message' + }, + } + + msg = ConversationClient('', http_client).create_message('conversation-id', data) + + self.assertEqual(datetime(2019, 4, 2, 11, 57, 53), msg.updatedDatetime) + self.assertEqual(datetime(2019, 4, 2, 11, 57, 52), msg.createdDatetime) + + http_client.request.assert_called_once_with('conversations/conversation-id/messages', 'POST', data) \ No newline at end of file From 2421f72924c744d8e1eaa9917bf5c329a3809b5b Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Tue, 2 Apr 2019 16:40:40 +0200 Subject: [PATCH 04/16] Add read_message method to the conversation client --- examples/conversation_create_message.py | 4 +-- examples/conversation_read_message.py | 47 +++++++++++++++++++++++++ tests/test_conversation_message.py | 8 +++++ 3 files changed, 57 insertions(+), 2 deletions(-) diff --git a/examples/conversation_create_message.py b/examples/conversation_create_message.py index a473b3b..34d0b0d 100644 --- a/examples/conversation_create_message.py +++ b/examples/conversation_create_message.py @@ -49,8 +49,8 @@ print(' content : %s' % msg.content) print(' status : %s' % msg.status) print(' type : %s' % msg.type) - print(' created date : %s' % msg.createdDateTime) - print(' updated date : %s' % msg.updatedDateTime) + print(' created date : %s' % msg.createdDatetime) + print(' updated date : %s' % msg.updatedDatetime) except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a Message object:\n') diff --git a/examples/conversation_read_message.py b/examples/conversation_read_message.py index e69de29..5957b7e 100644 --- a/examples/conversation_read_message.py +++ b/examples/conversation_read_message.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python + +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + +import messagebird + +# ACCESS_KEY = '' +# MESSAGE_ID = '' + +try: + ACCESS_KEY +except NameError: + print('You need to set an ACCESS_KEY constant in this file') + sys.exit(1) + +try: + MESSAGE_ID +except NameError: + print('You need to set a MESSAGE_ID constant in this file') + sys.exit(1) + + +try: + client = messagebird.ConversationClient(ACCESS_KEY) + + msg = client.read_message(MESSAGE_ID) + + # Print the object information. + print('\nThe following information was returned as a Conversation List object:\n') + print(' message id : %s' % msg.id) + print(' channel id : %s' % msg.channelId) + print(' direction : %s' % msg.direction) + print(' content : %s' % msg.content) + print(' content : %s' % msg.content) + print(' status : %s' % msg.status) + print(' type : %s' % msg.type) + print(' created date : %s' % msg.createdDatetime) + print(' updated date : %s' % msg.updatedDatetime) + +except messagebird.client.ErrorException as e: + print('\nAn error occured while requesting a Message object:\n') + + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/tests/test_conversation_message.py b/tests/test_conversation_message.py index a97516b..c6c096d 100644 --- a/tests/test_conversation_message.py +++ b/tests/test_conversation_message.py @@ -23,6 +23,14 @@ def test_conversation_list_messages(self): http_client.request.assert_called_once_with('conversations/54567/messages', 'GET', None) + def test_conversation_read_message(self): + http_client = Mock() + http_client.request.return_value = '{}' + + ConversationClient('', http_client).read_message('message-id') + + http_client.request.assert_called_once_with('messages/message-id', 'GET', None) + def test_create_message(self): http_client = Mock() http_client.request.return_value = '{"id":"id","conversationId":"conversation-id","channelId":"channel-id","type":"text","content":{"text":"Example Text Message"},"direction":"sent","status":"pending","createdDatetime":"2019-04-02T11:57:52.142641447Z","updatedDatetime":"2019-04-02T11:57:53.142641447Z"}' From d8da6c29e2bffed7d08c1b0607f337b36fe4f57e Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Tue, 2 Apr 2019 17:05:38 +0200 Subject: [PATCH 05/16] Add conversation list to conversation client --- examples/conversation_list.py | 38 ++++++++++++++++++++++++++ examples/conversation_list_messages.py | 8 +++--- messagebird/conversation.py | 22 ++++++++++++++- messagebird/conversation_client.py | 10 +++++-- tests/test_conversation.py | 10 ++++++- 5 files changed, 79 insertions(+), 9 deletions(-) create mode 100644 examples/conversation_list.py diff --git a/examples/conversation_list.py b/examples/conversation_list.py new file mode 100644 index 0000000..b53d607 --- /dev/null +++ b/examples/conversation_list.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python + +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + +import messagebird + +# ACCESS_KEY = '' + +try: + ACCESS_KEY +except NameError: + print('You need to set an ACCESS_KEY constant in this file') + sys.exit(1) + +try: + client = messagebird.ConversationClient(ACCESS_KEY) + + conversationList = client.list() + + itemIds = [] + for msgItem in conversationList.items: + itemIds.append(msgItem.id) + + # Print the object information. + print('\nThe following information was returned as a Conversation List object:\n') + print(' conversation ids : %s' % itemIds) + print(' offset : %s' % conversationList.offset) + print(' limit : %s' % conversationList.limit) + print(' totalCount : %s' % conversationList.totalCount) + +except messagebird.client.ErrorException as e: + print('\nAn error occured while requesting a Message object:\n') + + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) \ No newline at end of file diff --git a/examples/conversation_list_messages.py b/examples/conversation_list_messages.py index 9c87350..8c36765 100644 --- a/examples/conversation_list_messages.py +++ b/examples/conversation_list_messages.py @@ -30,14 +30,14 @@ itemIds.append(msgItem.id) # Print the object information. - print('\nThe following information was returned as a Conversation List object:\n') + print('\nThe following information was returned as a Conversation Message List object:\n') print(' message ids : %s' % itemIds) print(' offset : %s' % msg.offset) - print(' limit : %s', msg.limit) - print(' totalCount : %s', msg.totalCount) + print(' limit : %s' % msg.limit) + print(' totalCount : %s' % msg.totalCount) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Message object:\n') + print('\nAn error occured while requesting a Conversation Message List object:\n') for error in e.errors: print(' code : %d' % error.code) diff --git a/messagebird/conversation.py b/messagebird/conversation.py index ef5bd23..df85d7a 100644 --- a/messagebird/conversation.py +++ b/messagebird/conversation.py @@ -63,4 +63,24 @@ def lastReceivedDateTime(self): @lastReceivedDateTime.setter def lastReceivedDateTime(self, value): - self._lastReceivedDateTime = self.value_to_time(value) \ No newline at end of file + self._lastReceivedDateTime = self.value_to_time(value) + + +class ConversationList(Base): + def __init__(self): + self.offset = None + self.limit = None + self.count = None + self.totalCount = None + self._items = None + + @property + def items(self): + return self._items + + @items.setter + def items(self, value): + if isinstance(value, list): + self._items = [] + for item in value: + self._items.append(Conversation().load(item)) \ No newline at end of file diff --git a/messagebird/conversation_client.py b/messagebird/conversation_client.py index bb0143a..23a7b29 100644 --- a/messagebird/conversation_client.py +++ b/messagebird/conversation_client.py @@ -2,7 +2,7 @@ from messagebird.client import USER_AGENT, Client from messagebird.http_client import HttpClient from messagebird.conversation_message import ConversationMessage, ConversationMessageList -from messagebird.conversation import Conversation +from messagebird.conversation import Conversation, ConversationList try: from urllib.parse import urlencode @@ -25,8 +25,12 @@ def __init__(self, access_key, http_client=None): self.client = Client(access_key, http_client) - def list(self): - return self.access_key + def list(self, options=None): + uri = CONVERSATION_PATH + if options is not None: + uri += '?' + urlencode(options) + + return ConversationList().load(self.client.request(uri)) def start(self, start_request): uri = CONVERSATION_PATH + '/start' diff --git a/tests/test_conversation.py b/tests/test_conversation.py index 3721c56..10b25ce 100644 --- a/tests/test_conversation.py +++ b/tests/test_conversation.py @@ -33,4 +33,12 @@ def test_conversation_start(self): self.assertEqual(99999999999, msg.contact.msisdn) self.assertEqual(datetime(2019, 4, 2, 8, 19, 37), msg.contact.createdDatetime) self.assertEqual(datetime(2019, 4, 2, 8, 19, 38), msg.contact.updatedDatetime) - self.assertEqual('channel-name', msg.channels[0].name) \ No newline at end of file + self.assertEqual('channel-name', msg.channels[0].name) + + def test_conversation_list(self): + http_client = Mock() + http_client.request.return_value = '{}' + + ConversationClient('', http_client).list() + + http_client.request.assert_called_once_with('conversations', 'GET', None) \ No newline at end of file From 0bab52b2afe5e2c5f89c67dde530a058e45071c3 Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Wed, 3 Apr 2019 09:16:29 +0200 Subject: [PATCH 06/16] Add read conversation method to conversation client --- examples/conversation_read.py | 44 ++++++++++++++++++++++++++ messagebird/base.py | 7 +++++ messagebird/conversation.py | 49 +++++++++++++++++------------ messagebird/conversation_client.py | 3 +- messagebird/conversation_message.py | 9 +++--- tests/test_conversation.py | 18 ++++++++++- 6 files changed, 104 insertions(+), 26 deletions(-) create mode 100644 examples/conversation_read.py diff --git a/examples/conversation_read.py b/examples/conversation_read.py new file mode 100644 index 0000000..2c7cd21 --- /dev/null +++ b/examples/conversation_read.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python + +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + +import messagebird + +# ACCESS_KEY = '' +# CONVERSATION_ID = '' + +try: + ACCESS_KEY +except NameError: + print('You need to set an ACCESS_KEY constant in this file') + sys.exit(1) + +try: + CONVERSATION_ID +except NameError: + print('You need to set an CONVERSATION_ID constant in this file') + sys.exit(1) + +try: + client = messagebird.ConversationClient(ACCESS_KEY) + + conversation = client.read(CONVERSATION_ID) + + # Print the object information. + print('\nThe following information was returned as a Conversation object:\n') + print(' conversation id : %s' % conversation.id) + print(' contact id : %s' % conversation.contactId) + print(' messages total count : %s' % conversation.messages.totalCount) + print(' status : %s' % conversation.status) + print(' created date time : %s' % conversation.createdDatetime) + print(' updated date time : %s' % conversation.updatedDatetime) + print(' last received date time : %s' % conversation.lastReceivedDatetime) + +except messagebird.client.ErrorException as e: + print('\nAn error occured while requesting a Conversation object:\n') + + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) \ No newline at end of file diff --git a/messagebird/base.py b/messagebird/base.py index 7485f02..ee88e8e 100644 --- a/messagebird/base.py +++ b/messagebird/base.py @@ -8,6 +8,13 @@ def load(self, data): return self + def strip_nanoseconds_from_date(self, value): + if str(value).find(".") != -1: + return value[:-11] + value[-1:] + + return value + def value_to_time(self, value, format='%Y-%m-%dT%H:%M:%S+00:00'): if value != None: + value = self.strip_nanoseconds_from_date(value) return datetime.strptime(value, format) diff --git a/messagebird/conversation.py b/messagebird/conversation.py index df85d7a..591fa96 100644 --- a/messagebird/conversation.py +++ b/messagebird/conversation.py @@ -1,6 +1,7 @@ from messagebird.base import Base from messagebird.conversation_contact import ConversationContact from messagebird.conversation_channel import Channel +from messagebird.conversation_message import ConversationMessageReference CONVERSATION_STATUS_ACTIVE = "active" CONVERSATION_STATUS_ARCHIVED = "archived" @@ -13,12 +14,12 @@ def __init__(self): self.contactId = None self._contact = None self.lastUsedChannelId = None - self.channels = None - self.messages = None + self._channels = None + self._messages = None self.status = None - self._createdDateTime = None - self._updatedDateTime = None - self._lastReceivedDateTime = None + self._createdDatetime = None + self._updatedDatetime = None + self._lastReceivedDatetime = None @property def contact(self): @@ -28,6 +29,14 @@ def contact(self): def contact(self, value): self._contact = ConversationContact().load(value) + @property + def messages(self): + return self._messages + + @messages.setter + def messages(self, value): + self._messages = ConversationMessageReference().load(value) + @property def channels(self): return self._channels @@ -42,28 +51,28 @@ def channels(self, value): self._channels = value @property - def createdDateTime(self): - return self._createdDateTime + def createdDatetime(self): + return self._createdDatetime - @createdDateTime.setter - def createdDateTime(self, value): - self._createdDateTime = self.value_to_time(value) + @createdDatetime.setter + def createdDatetime(self, value): + self._createdDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') @property - def updatedDateTime(self): - return self._updatedDateTime + def updatedDatetime(self): + return self._updatedDatetime - @updatedDateTime.setter - def updatedDateTime(self, value): - self._updatedDateTime = self.value_to_time(value) + @updatedDatetime.setter + def updatedDatetime(self, value): + self._updatedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') @property - def lastReceivedDateTime(self): - return self._lastReceivedDateTime + def lastReceivedDatetime(self): + return self._lastReceivedDatetime - @lastReceivedDateTime.setter - def lastReceivedDateTime(self, value): - self._lastReceivedDateTime = self.value_to_time(value) + @lastReceivedDatetime.setter + def lastReceivedDatetime(self, value): + self._lastReceivedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') class ConversationList(Base): diff --git a/messagebird/conversation_client.py b/messagebird/conversation_client.py index 23a7b29..5b923af 100644 --- a/messagebird/conversation_client.py +++ b/messagebird/conversation_client.py @@ -40,7 +40,8 @@ def update(self, id): return self.access_key def read(self, id): - return self.access_key + uri = CONVERSATION_PATH + '/' + str(id) + return Conversation().load(self.client.request(uri)) def list_messages(self, conversation_id, options=None): uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH diff --git a/messagebird/conversation_message.py b/messagebird/conversation_message.py index e5f04ed..752d4b6 100644 --- a/messagebird/conversation_message.py +++ b/messagebird/conversation_message.py @@ -29,7 +29,6 @@ def createdDatetime(self): @createdDatetime.setter def createdDatetime(self, value): if value is not None: - value = self.strip_nanoseconds_from_date(value) self._createdDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') @property @@ -39,11 +38,13 @@ def updatedDatetime(self): @updatedDatetime.setter def updatedDatetime(self, value): if value is not None: - value = self.strip_nanoseconds_from_date(value) self._updatedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') - def strip_nanoseconds_from_date(self, value): - return value[:-11] + value[-1:] + +class ConversationMessageReference(Base): + def __init__(self): + self.totalCount = None + self.href = None class ConversationMessageList(Base): diff --git a/tests/test_conversation.py b/tests/test_conversation.py index 10b25ce..ddaf40a 100644 --- a/tests/test_conversation.py +++ b/tests/test_conversation.py @@ -41,4 +41,20 @@ def test_conversation_list(self): ConversationClient('', http_client).list() - http_client.request.assert_called_once_with('conversations', 'GET', None) \ No newline at end of file + http_client.request.assert_called_once_with('conversations', 'GET', None) + + def test_conversation_read(self): + http_client = Mock() + http_client.request.return_value = '{"id":"57b96dbe0fda40f0a814f5e3268c30a9","contactId":"8846d44229094c20813cf9eea596e680","contact":{"id":"8846d44229094c20813cf9eea596e680","href":"https://contacts.messagebird.com/v2/contacts/8846d44229094c20813cf9eea596e680","msisdn":31617110163,"displayName":"31617110163","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:54:39Z","updatedDatetime":"2019-04-02T08:54:40Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:54:38Z","updatedDatetime":"2019-04-02T14:24:09.192202886Z","lastReceivedDatetime":"2019-04-02T14:24:09.14826339Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":2,"href":"https://conversations.messagebird.com/v1/conversations/57b96dbe0fda40f0a814f5e3268c30a9/messages"}}' + + conversation = ConversationClient('', http_client).read('conversation-id') + + http_client.request.assert_called_once_with('conversations/conversation-id', 'GET', None) + + self.assertEqual('57b96dbe0fda40f0a814f5e3268c30a9', conversation.id) + self.assertEqual(datetime(2019, 4, 2, 8, 54, 38), conversation.createdDatetime) + self.assertEqual(datetime(2019, 4, 2, 14, 24, 9), conversation.updatedDatetime) + self.assertEqual(datetime(2019, 4, 2, 14, 24), conversation.lastReceivedDatetime) + self.assertEqual('8846d44229094c20813cf9eea596e680', conversation.contact.id) + self.assertEqual('c0dae31e440145e094c4708b7d908842', conversation.channels[0].id) + self.assertEqual(2, conversation.messages.totalCount) \ No newline at end of file From 05f683d34cd65c82cc944dd382be3bc972ea3bf4 Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Wed, 3 Apr 2019 09:36:43 +0200 Subject: [PATCH 07/16] Add conversation update method --- examples/conversation_update.py | 44 ++++++++++++++++++++++++++++++ messagebird/conversation_client.py | 5 ++-- tests/test_conversation.py | 13 ++++++++- 3 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 examples/conversation_update.py diff --git a/examples/conversation_update.py b/examples/conversation_update.py new file mode 100644 index 0000000..16fb4d7 --- /dev/null +++ b/examples/conversation_update.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python + +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + +import messagebird + +# ACCESS_KEY = '' +# CONVERSATION_ID = '' + +try: + ACCESS_KEY +except NameError: + print('You need to set an ACCESS_KEY constant in this file') + sys.exit(1) + +try: + CONVERSATION_ID +except NameError: + print('You need to set an CONVERSATION_ID constant in this file') + sys.exit(1) + +try: + client = messagebird.ConversationClient(ACCESS_KEY) + + conversation = client.update(CONVERSATION_ID, {'status': 'active'}) + + # Print the object information. + print('\nThe following information was returned as a Conversation object:\n') + print(' conversation id : %s' % conversation.id) + print(' contact id : %s' % conversation.contactId) + print(' messages total count : %s' % conversation.messages.totalCount) + print(' status : %s' % conversation.status) + print(' created date time : %s' % conversation.createdDatetime) + print(' updated date time : %s' % conversation.updatedDatetime) + print(' last received date time : %s' % conversation.lastReceivedDatetime) + +except messagebird.client.ErrorException as e: + print('\nAn error occured while requesting a Conversation object:\n') + + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) \ No newline at end of file diff --git a/messagebird/conversation_client.py b/messagebird/conversation_client.py index 5b923af..484f1ad 100644 --- a/messagebird/conversation_client.py +++ b/messagebird/conversation_client.py @@ -36,8 +36,9 @@ def start(self, start_request): uri = CONVERSATION_PATH + '/start' return Conversation().load(self.client.request(uri, 'POST', start_request)) - def update(self, id): - return self.access_key + def update(self, id, update_request): + uri = CONVERSATION_PATH + '/' + str(id) + return Conversation().load(self.client.request(uri, 'PATCH', update_request)) def read(self, id): uri = CONVERSATION_PATH + '/' + str(id) diff --git a/tests/test_conversation.py b/tests/test_conversation.py index ddaf40a..b97e479 100644 --- a/tests/test_conversation.py +++ b/tests/test_conversation.py @@ -57,4 +57,15 @@ def test_conversation_read(self): self.assertEqual(datetime(2019, 4, 2, 14, 24), conversation.lastReceivedDatetime) self.assertEqual('8846d44229094c20813cf9eea596e680', conversation.contact.id) self.assertEqual('c0dae31e440145e094c4708b7d908842', conversation.channels[0].id) - self.assertEqual(2, conversation.messages.totalCount) \ No newline at end of file + self.assertEqual(2, conversation.messages.totalCount) + + def test_conversation_update(self): + http_client = Mock() + http_client.request.return_value = '{"id":"07e823fdb36a462fb5e187d6d7b96493","contactId":"459a35432b0c4195abbdae353eb19359","status":"archived","createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-03T07:22:58.965421128Z","lastReceivedDatetime":"2019-04-02T12:02:22.707634424Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":16,"href":"https://conversations.messagebird.com/v1/conversations/07e823fdb36a462fb5e187d6d7b96493/messages"}}' + + updatedRequestData = {'status': 'archived'} + + conversation = ConversationClient('', http_client).update('conversation-id', updatedRequestData) + + http_client.request.assert_called_once_with('conversations/conversation-id', 'PATCH', updatedRequestData) + self.assertEqual('archived', conversation.status) \ No newline at end of file From ecb55a5b0faa8220d82eb8a14f03ec6eb8c8bccb Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Wed, 3 Apr 2019 09:56:57 +0200 Subject: [PATCH 08/16] Add create conversation webhook method --- examples/conversation_create_webhook.py | 49 +++++++++++++++++++++++++ messagebird/conversation_client.py | 5 ++- messagebird/conversation_webhook.py | 29 ++++++++++++++- tests/test_conversation_webhook.py | 30 +++++++++++++++ 4 files changed, 109 insertions(+), 4 deletions(-) create mode 100644 examples/conversation_create_webhook.py create mode 100644 tests/test_conversation_webhook.py diff --git a/examples/conversation_create_webhook.py b/examples/conversation_create_webhook.py new file mode 100644 index 0000000..c91d472 --- /dev/null +++ b/examples/conversation_create_webhook.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python + +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + +import messagebird +from messagebird.conversation_webhook import \ + CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED,\ + CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED + +# ACCESS_KEY = '' +# CHANNEL_ID = '' + +try: + ACCESS_KEY +except NameError: + print('You need to set an ACCESS_KEY constant in this file') + sys.exit(1) + +try: + CHANNEL_ID +except NameError: + print('You need to set an CHANNEL_ID constant in this file') + sys.exit(1) + +try: + client = messagebird.ConversationClient(ACCESS_KEY) + + webhook = client.create_webhook({ + 'channelId': CHANNEL_ID, + 'events': [CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED, CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED], + 'url': 'https://example.com' + }) + + # Print the object information. + print('\nThe following information was returned as a Conversation List object:\n') + print(' id : %s' % webhook.id) + print(' events : %s' % webhook.events) + print(' channel id : %s' % webhook.channelId) + print(' created date : %s' % webhook.createdDatetime) + print(' updated date : %s' % webhook.updatedDatetime) + +except messagebird.client.ErrorException as e: + print('\nAn error occured while requesting a Message object:\n') + + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) \ No newline at end of file diff --git a/messagebird/conversation_client.py b/messagebird/conversation_client.py index 484f1ad..d1ee64b 100644 --- a/messagebird/conversation_client.py +++ b/messagebird/conversation_client.py @@ -3,6 +3,7 @@ from messagebird.http_client import HttpClient from messagebird.conversation_message import ConversationMessage, ConversationMessageList from messagebird.conversation import Conversation, ConversationList +from messagebird.conversation_webhook import ConversationWebhook try: from urllib.parse import urlencode @@ -60,8 +61,8 @@ def read_message(self, message_id): uri = CONVERSATION_MESSAGES_PATH + '/' + str(message_id) return ConversationMessage().load(self.client.request(uri)) - def create_webhook(self): - return self.access_key + def create_webhook(self, webhook_create_request): + return ConversationWebhook().load(self.client.request(CONVERSATION_WEB_HOOKS_PATH, 'POST', webhook_create_request)) def delete_webhook(self): return self.access_key diff --git a/messagebird/conversation_webhook.py b/messagebird/conversation_webhook.py index 7a3c6c8..8f7ae8c 100644 --- a/messagebird/conversation_webhook.py +++ b/messagebird/conversation_webhook.py @@ -1,8 +1,33 @@ from messagebird.base import Base -class ConversationWebhookCreateRequest(Base): +CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED = 'conversation.created' +CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED = 'conversation.updated' +CONVERSATION_WEBHOOK_EVENT_MESSAGE_CREATED = 'message.created' +CONVERSATION_WEBHOOK_EVENT_MESSAGE_UPDATED = 'message.updated' + + +class ConversationWebhook(Base): def __init__(self): + self.id = None self.channelId = None - self.events = None self.url = None + self.events = None + self._createdDatetime = None + self._updatedDatetime = None + + @property + def createdDatetime(self): + return self._createdDatetime + + @createdDatetime.setter + def createdDatetime(self, value): + self._createdDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') + + @property + def updatedDatetime(self): + return self._updatedDatetime + + @updatedDatetime.setter + def updatedDatetime(self, value): + self._updatedDatetime = self.value_to_time(value) \ No newline at end of file diff --git a/tests/test_conversation_webhook.py b/tests/test_conversation_webhook.py new file mode 100644 index 0000000..a6ad8d8 --- /dev/null +++ b/tests/test_conversation_webhook.py @@ -0,0 +1,30 @@ +import unittest +from datetime import datetime +from messagebird import ConversationClient +from messagebird.conversation_webhook import \ + CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED,\ + CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED + +try: + from unittest.mock import Mock +except ImportError: + # mock was added to unittest in Python 3.3, but was an external library + # before. + from mock import Mock + + +class TestConversationWebhook(unittest.TestCase): + + def test_conversation_webhook_create(self): + http_client = Mock() + http_client.request.return_value = '{"id":"20c308852190485bbb658e43baffc5fa","url":"https://example.com","channelId":"c0dae31e440145e094c4708b7d908842","events":["conversation.created","conversation.updated"],"status":"enabled","createdDatetime":"2019-04-03T07:46:37.984026573Z","updatedDatetime":null}' + + webhookRequestData = { + 'channelId': '20c308852190485bbb658e43baffc5fa', + 'events': [CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED, CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED], + 'url': 'https://example.com' + } + + ConversationClient('', http_client).create_webhook(webhookRequestData) + + http_client.request.assert_called_once_with('webhooks', 'POST', webhookRequestData) \ No newline at end of file From d14c0fa6b4944ea463cec5ea8d26cb2de7332e7f Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Wed, 3 Apr 2019 10:37:54 +0200 Subject: [PATCH 09/16] Add delete, list webhook methods --- examples/conversation_create_webhook.py | 4 +-- examples/conversation_delete_webhook.py | 37 ++++++++++++++++++++++++ examples/conversation_list_webhook.py | 38 +++++++++++++++++++++++++ messagebird/client.py | 4 +++ messagebird/conversation_client.py | 15 ++++++---- messagebird/conversation_webhook.py | 24 +++++++++++++++- tests/test_conversation_webhook.py | 26 ++++++++++++++++- 7 files changed, 139 insertions(+), 9 deletions(-) create mode 100644 examples/conversation_delete_webhook.py create mode 100644 examples/conversation_list_webhook.py diff --git a/examples/conversation_create_webhook.py b/examples/conversation_create_webhook.py index c91d472..ba7d661 100644 --- a/examples/conversation_create_webhook.py +++ b/examples/conversation_create_webhook.py @@ -33,7 +33,7 @@ }) # Print the object information. - print('\nThe following information was returned as a Conversation List object:\n') + print('\nThe following information was returned as a Webhook object:\n') print(' id : %s' % webhook.id) print(' events : %s' % webhook.events) print(' channel id : %s' % webhook.channelId) @@ -41,7 +41,7 @@ print(' updated date : %s' % webhook.updatedDatetime) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Message object:\n') + print('\nAn error occured while requesting a Webhook object:\n') for error in e.errors: print(' code : %d' % error.code) diff --git a/examples/conversation_delete_webhook.py b/examples/conversation_delete_webhook.py new file mode 100644 index 0000000..452768f --- /dev/null +++ b/examples/conversation_delete_webhook.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python + +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + +import messagebird + +# ACCESS_KEY = '' +# WEBHOOK_ID = '' + +try: + ACCESS_KEY +except NameError: + print('You need to set an ACCESS_KEY constant in this file') + sys.exit(1) + +try: + WEBHOOK_ID +except NameError: + print('You need to set an WEBHOOK_ID constant in this file') + sys.exit(1) + +try: + client = messagebird.ConversationClient(ACCESS_KEY) + + client.delete_webhook(WEBHOOK_ID) + + # Print the object information. + print('\nWebhook has been deleted:\n') + +except messagebird.client.ErrorException as e: + print('\nAn error occured while requesting a Webhook object:\n') + + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) \ No newline at end of file diff --git a/examples/conversation_list_webhook.py b/examples/conversation_list_webhook.py new file mode 100644 index 0000000..2cc217d --- /dev/null +++ b/examples/conversation_list_webhook.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python + +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + +import messagebird + +# ACCESS_KEY = '' + +try: + ACCESS_KEY +except NameError: + print('You need to set an ACCESS_KEY constant in this file') + sys.exit(1) + +try: + client = messagebird.ConversationClient(ACCESS_KEY) + + webhookList = client.list() + + itemIds = [] + for msgItem in webhookList.items: + itemIds.append(msgItem.id) + + # Print the object information. + print('\nThe following information was returned as a Conversation Webhook List object:\n') + print(' conversation ids : %s' % itemIds) + print(' offset : %s' % webhookList.offset) + print(' limit : %s' % webhookList.limit) + print(' totalCount : %s' % webhookList.totalCount) + +except messagebird.client.ErrorException as e: + print('\nAn error occured while requesting a Conversation Webhook List object:\n') + + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) \ No newline at end of file diff --git a/messagebird/client.py b/messagebird/client.py index 9803e54..bc7f9ec 100644 --- a/messagebird/client.py +++ b/messagebird/client.py @@ -38,6 +38,10 @@ def __init__(self, access_key, http_client=None): def request(self, path, method='GET', params=None): """Builds a request, gets a response and decodes it.""" response_text = self.http_client.request(path, method, params) + + if not response_text: + return response_text + response_json = json.loads(response_text) if 'errors' in response_json: diff --git a/messagebird/conversation_client.py b/messagebird/conversation_client.py index d1ee64b..dc00d4f 100644 --- a/messagebird/conversation_client.py +++ b/messagebird/conversation_client.py @@ -3,7 +3,7 @@ from messagebird.http_client import HttpClient from messagebird.conversation_message import ConversationMessage, ConversationMessageList from messagebird.conversation import Conversation, ConversationList -from messagebird.conversation_webhook import ConversationWebhook +from messagebird.conversation_webhook import ConversationWebhook, ConversationWebhookList try: from urllib.parse import urlencode @@ -64,11 +64,16 @@ def read_message(self, message_id): def create_webhook(self, webhook_create_request): return ConversationWebhook().load(self.client.request(CONVERSATION_WEB_HOOKS_PATH, 'POST', webhook_create_request)) - def delete_webhook(self): - return self.access_key + def delete_webhook(self, id): + uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id) + self.client.request(uri, 'DELETE') - def list_webhooks(self): - return self.access_key + def list_webhooks(self, options=None): + uri = CONVERSATION_WEB_HOOKS_PATH + if options is not None: + uri += '?' + urlencode(options) + + return ConversationWebhookList().load(self.client.request(uri)) def read_webhook(self): return self.access_key \ No newline at end of file diff --git a/messagebird/conversation_webhook.py b/messagebird/conversation_webhook.py index 8f7ae8c..727d51c 100644 --- a/messagebird/conversation_webhook.py +++ b/messagebird/conversation_webhook.py @@ -30,4 +30,26 @@ def updatedDatetime(self): @updatedDatetime.setter def updatedDatetime(self, value): - self._updatedDatetime = self.value_to_time(value) \ No newline at end of file + self._updatedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') + + +class ConversationWebhookList(Base): + def __init__(self): + self.offset = None + self.limit = None + self.count = None + self.totalCount = None + self._items = None + + @property + def items(self): + return self._items + + @items.setter + def items(self, value): + items = [] + if isinstance(value, list): + for item in value: + items.append(ConversationWebhook().load(item)) + + self._items = items diff --git a/tests/test_conversation_webhook.py b/tests/test_conversation_webhook.py index a6ad8d8..1fb9089 100644 --- a/tests/test_conversation_webhook.py +++ b/tests/test_conversation_webhook.py @@ -27,4 +27,28 @@ def test_conversation_webhook_create(self): ConversationClient('', http_client).create_webhook(webhookRequestData) - http_client.request.assert_called_once_with('webhooks', 'POST', webhookRequestData) \ No newline at end of file + http_client.request.assert_called_once_with('webhooks', 'POST', webhookRequestData) + + def test_conversation_webhook_delete(self): + http_client = Mock() + http_client.request.return_value = '' + + ConversationClient('', http_client).delete_webhook('webhook-id') + + http_client.request.assert_called_once_with('webhooks/webhook-id', 'DELETE', None) + + + def test_conversation_webhook_list(self): + http_client = Mock() + http_client.request.return_value = '{"offset":0,"limit":10,"count":2,"totalCount":2,"items":[{"id":"57b96dbe0fda40f0a814f5e3268c30a9","contactId":"8846d44229094c20813cf9eea596e680","contact":{"id":"8846d44229094c20813cf9eea596e680","href":"https://contacts.messagebird.com/v2/contacts/8846d44229094c20813cf9eea596e680","msisdn":31617110163,"displayName":"31617110163","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:54:39Z","updatedDatetime":"2019-04-02T08:54:40Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:54:38Z","updatedDatetime":"2019-04-02T14:24:09.192202886Z","lastReceivedDatetime":"2019-04-02T14:24:09.14826339Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":2,"href":"https://conversations.messagebird.com/v1/conversations/57b96dbe0fda40f0a814f5e3268c30a9/messages"}},{"id":"07e823fdb36a462fb5e187d6d7b96493","contactId":"459a35432b0c4195abbdae353eb19359","contact":{"id":"459a35432b0c4195abbdae353eb19359","href":"https://contacts.messagebird.com/v2/contacts/459a35432b0c4195abbdae353eb19359","msisdn":31615164888,"displayName":"31615164888","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:19:38Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-03T07:35:47.35395356Z","lastReceivedDatetime":"2019-04-02T12:02:22.707634424Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":16,"href":"https://conversations.messagebird.com/v1/conversations/07e823fdb36a462fb5e187d6d7b96493/messages"}}]}' + + ConversationClient('', http_client).list_webhooks() + http_client.request.assert_called_once_with('webhooks', 'GET', None) + + def test_conversation_webhook_list_pagination(self): + http_client = Mock() + http_client.request.return_value = '{"offset":0,"limit":10,"count":2,"totalCount":2,"items":[{"id":"57b96dbe0fda40f0a814f5e3268c30a9","contactId":"8846d44229094c20813cf9eea596e680","contact":{"id":"8846d44229094c20813cf9eea596e680","href":"https://contacts.messagebird.com/v2/contacts/8846d44229094c20813cf9eea596e680","msisdn":31617110163,"displayName":"31617110163","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:54:39Z","updatedDatetime":"2019-04-02T08:54:40Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:54:38Z","updatedDatetime":"2019-04-02T14:24:09.192202886Z","lastReceivedDatetime":"2019-04-02T14:24:09.14826339Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":2,"href":"https://conversations.messagebird.com/v1/conversations/57b96dbe0fda40f0a814f5e3268c30a9/messages"}},{"id":"07e823fdb36a462fb5e187d6d7b96493","contactId":"459a35432b0c4195abbdae353eb19359","contact":{"id":"459a35432b0c4195abbdae353eb19359","href":"https://contacts.messagebird.com/v2/contacts/459a35432b0c4195abbdae353eb19359","msisdn":31615164888,"displayName":"31615164888","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:19:38Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-03T07:35:47.35395356Z","lastReceivedDatetime":"2019-04-02T12:02:22.707634424Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":16,"href":"https://conversations.messagebird.com/v1/conversations/07e823fdb36a462fb5e187d6d7b96493/messages"}}]}' + + params = {'offset': 1, 'limit': 2} + ConversationClient('', http_client).list_webhooks(params) + http_client.request.assert_called_once_with('webhooks?offset=1&limit=2', 'GET', None) From 5ae0c1f37195f6df837b882c7168e685af3ddc61 Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Wed, 3 Apr 2019 10:45:05 +0200 Subject: [PATCH 10/16] Add read webhook method --- examples/conversation_read_webhook.py | 42 +++++++++++++++++++++++++++ messagebird/conversation_client.py | 5 ++-- tests/test_conversation_webhook.py | 11 +++++++ 3 files changed, 56 insertions(+), 2 deletions(-) create mode 100644 examples/conversation_read_webhook.py diff --git a/examples/conversation_read_webhook.py b/examples/conversation_read_webhook.py new file mode 100644 index 0000000..a34e09f --- /dev/null +++ b/examples/conversation_read_webhook.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python + +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + +import messagebird + +# ACCESS_KEY = '' +# WEBHOOK_ID = '' + +try: + ACCESS_KEY +except NameError: + print('You need to set an ACCESS_KEY constant in this file') + sys.exit(1) + +try: + WEBHOOK_ID +except NameError: + print('You need to set an WEBHOOK_ID constant in this file') + sys.exit(1) + +try: + client = messagebird.ConversationClient(ACCESS_KEY) + + webhook = client.read_webhook(WEBHOOK_ID) + + # Print the object information. + print('\nThe following information was returned as a Webhook object:\n') + print(' id : %s' % webhook.id) + print(' events : %s' % webhook.events) + print(' channel id : %s' % webhook.channelId) + print(' created date : %s' % webhook.createdDatetime) + print(' updated date : %s' % webhook.updatedDatetime) + +except messagebird.client.ErrorException as e: + print('\nAn error occured while requesting a Webhook object:\n') + + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) \ No newline at end of file diff --git a/messagebird/conversation_client.py b/messagebird/conversation_client.py index dc00d4f..ebb2d93 100644 --- a/messagebird/conversation_client.py +++ b/messagebird/conversation_client.py @@ -75,5 +75,6 @@ def list_webhooks(self, options=None): return ConversationWebhookList().load(self.client.request(uri)) - def read_webhook(self): - return self.access_key \ No newline at end of file + def read_webhook(self, id): + uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id) + return ConversationWebhook().load(self.client.request(uri)) \ No newline at end of file diff --git a/tests/test_conversation_webhook.py b/tests/test_conversation_webhook.py index 1fb9089..5a04549 100644 --- a/tests/test_conversation_webhook.py +++ b/tests/test_conversation_webhook.py @@ -52,3 +52,14 @@ def test_conversation_webhook_list_pagination(self): params = {'offset': 1, 'limit': 2} ConversationClient('', http_client).list_webhooks(params) http_client.request.assert_called_once_with('webhooks?offset=1&limit=2', 'GET', None) + + def test_conversation_webhook_read(self): + http_client = Mock() + http_client.request.return_value = '{"id":"5031e2da142d401c93fbc38518ebb604","url":"https://example.com","channelId":"c0dae31e440145e094c4708b7d908842","events":["conversation.created","conversation.updated"],"status":"enabled","createdDatetime":"2019-04-03T08:41:37Z","updatedDatetime":null}' + + webhook = ConversationClient('', http_client).read_webhook('webhook-id') + + http_client.request.assert_called_once_with('webhooks/webhook-id', 'GET', None) + self.assertEqual(datetime(2019, 4, 3, 8, 41, 37), webhook.createdDatetime) + self.assertEqual(None, webhook.updatedDatetime) + self.assertEqual(['conversation.created', 'conversation.updated'], webhook.events) \ No newline at end of file From 380069a0872e7f0cb83658df8fb7f75a4591093e Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Wed, 3 Apr 2019 11:04:23 +0200 Subject: [PATCH 11/16] Add all conversation methods to Client and remove ConversationClient --- examples/conversation_create_message.py | 4 +- examples/conversation_create_webhook.py | 4 +- examples/conversation_delete_webhook.py | 4 +- examples/conversation_list.py | 4 +- examples/conversation_list_messages.py | 4 +- examples/conversation_list_webhook.py | 4 +- examples/conversation_read.py | 4 +- examples/conversation_read_message.py | 4 +- examples/conversation_read_webhook.py | 4 +- examples/conversation_start.py | 4 +- examples/conversation_update.py | 4 +- messagebird/__init__.py | 1 - messagebird/client.py | 110 ++++++++++++++++++++---- messagebird/conversation_client.py | 80 ----------------- tests/test_conversation.py | 10 +-- tests/test_conversation_message.py | 8 +- tests/test_conversation_webhook.py | 13 ++- 17 files changed, 128 insertions(+), 138 deletions(-) delete mode 100644 messagebird/conversation_client.py diff --git a/examples/conversation_create_message.py b/examples/conversation_create_message.py index 34d0b0d..a586503 100644 --- a/examples/conversation_create_message.py +++ b/examples/conversation_create_message.py @@ -36,9 +36,9 @@ sys.exit(1) try: - client = messagebird.ConversationClient(ACCESS_KEY) + client = messagebird.Client(ACCESS_KEY) - msg = client.create_message(CONVERSATION_ID, { 'channelId': CHANNEL_ID, 'type': MESSAGE_TYPE_TEXT, 'content': { 'text': TEXT_MESSAGE } }) + msg = client.conversation_create_message(CONVERSATION_ID, { 'channelId': CHANNEL_ID, 'type': MESSAGE_TYPE_TEXT, 'content': { 'text': TEXT_MESSAGE } }) # Print the object information. print('\nThe following information was returned as a Conversation List object:\n') diff --git a/examples/conversation_create_webhook.py b/examples/conversation_create_webhook.py index ba7d661..b94b1e9 100644 --- a/examples/conversation_create_webhook.py +++ b/examples/conversation_create_webhook.py @@ -24,9 +24,9 @@ sys.exit(1) try: - client = messagebird.ConversationClient(ACCESS_KEY) + client = messagebird.Client(ACCESS_KEY) - webhook = client.create_webhook({ + webhook = client.conversation_create_webhook({ 'channelId': CHANNEL_ID, 'events': [CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED, CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED], 'url': 'https://example.com' diff --git a/examples/conversation_delete_webhook.py b/examples/conversation_delete_webhook.py index 452768f..f7f6374 100644 --- a/examples/conversation_delete_webhook.py +++ b/examples/conversation_delete_webhook.py @@ -21,9 +21,9 @@ sys.exit(1) try: - client = messagebird.ConversationClient(ACCESS_KEY) + client = messagebird.Client(ACCESS_KEY) - client.delete_webhook(WEBHOOK_ID) + client.conversation_delete_webhook(WEBHOOK_ID) # Print the object information. print('\nWebhook has been deleted:\n') diff --git a/examples/conversation_list.py b/examples/conversation_list.py index b53d607..40dbde7 100644 --- a/examples/conversation_list.py +++ b/examples/conversation_list.py @@ -14,9 +14,9 @@ sys.exit(1) try: - client = messagebird.ConversationClient(ACCESS_KEY) + client = messagebird.Client(ACCESS_KEY) - conversationList = client.list() + conversationList = client.conversation_list() itemIds = [] for msgItem in conversationList.items: diff --git a/examples/conversation_list_messages.py b/examples/conversation_list_messages.py index 8c36765..7ff5f44 100644 --- a/examples/conversation_list_messages.py +++ b/examples/conversation_list_messages.py @@ -21,9 +21,9 @@ sys.exit(1) try: - client = messagebird.ConversationClient(ACCESS_KEY) + client = messagebird.Client(ACCESS_KEY) - msg = client.list_messages(CONVERSATION_ID) + msg = client.conversation_list_messages(CONVERSATION_ID) itemIds = [] for msgItem in msg.items: diff --git a/examples/conversation_list_webhook.py b/examples/conversation_list_webhook.py index 2cc217d..453127a 100644 --- a/examples/conversation_list_webhook.py +++ b/examples/conversation_list_webhook.py @@ -14,9 +14,9 @@ sys.exit(1) try: - client = messagebird.ConversationClient(ACCESS_KEY) + client = messagebird.Client(ACCESS_KEY) - webhookList = client.list() + webhookList = client.conversation_list_webhooks() itemIds = [] for msgItem in webhookList.items: diff --git a/examples/conversation_read.py b/examples/conversation_read.py index 2c7cd21..5ff1e0f 100644 --- a/examples/conversation_read.py +++ b/examples/conversation_read.py @@ -21,9 +21,9 @@ sys.exit(1) try: - client = messagebird.ConversationClient(ACCESS_KEY) + client = messagebird.Client(ACCESS_KEY) - conversation = client.read(CONVERSATION_ID) + conversation = client.conversation_read(CONVERSATION_ID) # Print the object information. print('\nThe following information was returned as a Conversation object:\n') diff --git a/examples/conversation_read_message.py b/examples/conversation_read_message.py index 5957b7e..87cbced 100644 --- a/examples/conversation_read_message.py +++ b/examples/conversation_read_message.py @@ -22,9 +22,9 @@ try: - client = messagebird.ConversationClient(ACCESS_KEY) + client = messagebird.Client(ACCESS_KEY) - msg = client.read_message(MESSAGE_ID) + msg = client.conversation_read_message(MESSAGE_ID) # Print the object information. print('\nThe following information was returned as a Conversation List object:\n') diff --git a/examples/conversation_read_webhook.py b/examples/conversation_read_webhook.py index a34e09f..9d62430 100644 --- a/examples/conversation_read_webhook.py +++ b/examples/conversation_read_webhook.py @@ -21,9 +21,9 @@ sys.exit(1) try: - client = messagebird.ConversationClient(ACCESS_KEY) + client = messagebird.Client(ACCESS_KEY) - webhook = client.read_webhook(WEBHOOK_ID) + webhook = client.conversation_read_webhook(WEBHOOK_ID) # Print the object information. print('\nThe following information was returned as a Webhook object:\n') diff --git a/examples/conversation_start.py b/examples/conversation_start.py index 4eb89d1..8e91d9a 100644 --- a/examples/conversation_start.py +++ b/examples/conversation_start.py @@ -36,9 +36,9 @@ sys.exit(1) try: - client = messagebird.ConversationClient(ACCESS_KEY) + client = messagebird.Client(ACCESS_KEY) - msg = client.start({ 'channelId': CHANNEL_ID, 'to': PHONE_NUMBER, 'type': MESSAGE_TYPE_TEXT, 'content': { 'text': TEXT_MESSAGE } }) + msg = client.conversation_start({ 'channelId': CHANNEL_ID, 'to': PHONE_NUMBER, 'type': MESSAGE_TYPE_TEXT, 'content': { 'text': TEXT_MESSAGE } }) # Print the object information. print('\nThe following information was returned as a Conversation object:\n') diff --git a/examples/conversation_update.py b/examples/conversation_update.py index 16fb4d7..ef9996d 100644 --- a/examples/conversation_update.py +++ b/examples/conversation_update.py @@ -21,9 +21,9 @@ sys.exit(1) try: - client = messagebird.ConversationClient(ACCESS_KEY) + client = messagebird.Client(ACCESS_KEY) - conversation = client.update(CONVERSATION_ID, {'status': 'active'}) + conversation = client.conversation_update(CONVERSATION_ID, {'status': 'active'}) # Print the object information. print('\nThe following information was returned as a Conversation object:\n') diff --git a/messagebird/__init__.py b/messagebird/__init__.py index 94f4461..cf57a14 100644 --- a/messagebird/__init__.py +++ b/messagebird/__init__.py @@ -1,2 +1 @@ from messagebird.client import Client, ErrorException -from messagebird.conversation_client import ConversationClient diff --git a/messagebird/client.py b/messagebird/client.py index bc7f9ec..34dc464 100644 --- a/messagebird/client.py +++ b/messagebird/client.py @@ -1,22 +1,36 @@ import sys import json -from messagebird.base import Base -from messagebird.balance import Balance -from messagebird.contact import Contact, ContactList -from messagebird.error import Error -from messagebird.group import ContactReference, Group, GroupList -from messagebird.hlr import HLR -from messagebird.http_client import HttpClient -from messagebird.message import Message -from messagebird.voicemessage import VoiceMessage -from messagebird.lookup import Lookup -from messagebird.verify import Verify +from messagebird.balance import Balance +from messagebird.contact import Contact, ContactList +from messagebird.error import Error +from messagebird.group import Group, GroupList +from messagebird.hlr import HLR +from messagebird.message import Message +from messagebird.voicemessage import VoiceMessage +from messagebird.lookup import Lookup +from messagebird.verify import Verify +from messagebird.http_client import HttpClient +from messagebird.conversation_message import ConversationMessage, ConversationMessageList +from messagebird.conversation import Conversation, ConversationList +from messagebird.conversation_webhook import ConversationWebhook, ConversationWebhookList + +try: + from urllib.parse import urlencode +except ImportError: + from urllib import urlencode ENDPOINT = 'https://rest.messagebird.com' CLIENT_VERSION = '1.3.1' PYTHON_VERSION = '%d.%d.%d' % (sys.version_info[0], sys.version_info[1], sys.version_info[2]) USER_AGENT = 'MessageBird/ApiClient/%s Python/%s' % (CLIENT_VERSION, PYTHON_VERSION) +REST_TYPE = 'rest' + +CONVERSATION_API_ROOT = 'https://conversations.messagebird.com/v1/' +CONVERSATION_PATH = 'conversations' +CONVERSATION_MESSAGES_PATH = 'messages' +CONVERSATION_WEB_HOOKS_PATH = 'webhooks' +CONVERSATION_TYPE = 'conversation' class ErrorException(Exception): @@ -29,15 +43,20 @@ def __init__(self, errors): class Client(object): def __init__(self, access_key, http_client=None): self.access_key = access_key + self.http_client = http_client + + def getHttpClient(self, type=REST_TYPE): + if self.http_client: + return self.http_client + + if type == REST_TYPE: + return HttpClient(ENDPOINT, self.access_key, USER_AGENT) - if http_client is None: - self.http_client = HttpClient(ENDPOINT, access_key, USER_AGENT) - else: - self.http_client = http_client + return HttpClient(CONVERSATION_API_ROOT, self.access_key, USER_AGENT) - def request(self, path, method='GET', params=None): + def request(self, path, method='GET', params=None, type=REST_TYPE): """Builds a request, gets a response and decodes it.""" - response_text = self.http_client.request(path, method, params) + response_text = self.getHttpClient(type).request(path, method, params) if not response_text: return response_text @@ -49,9 +68,9 @@ def request(self, path, method='GET', params=None): return response_json - def request_plain_text(self, path, method='GET', params=None): + def request_plain_text(self, path, method='GET', params=None, type=REST_TYPE): """Builds a request, gets a response and returns the body.""" - response_text = self.http_client.request(path, method, params) + response_text = self.getHttpClient(type).request(path, method, params) try: # Try to decode the response to JSON to see if the API returned any @@ -189,3 +208,56 @@ def __group_add_contacts_query(self, contactIds): def group_remove_contact(self, groupId, contactId): self.request_plain_text('groups/' + str(groupId) + '/contacts/' + str(contactId), 'DELETE', None) + + def conversation_list(self, options=None): + uri = CONVERSATION_PATH + if options is not None: + uri += '?' + urlencode(options) + + return ConversationList().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) + + def conversation_start(self, start_request): + uri = CONVERSATION_PATH + '/start' + return Conversation().load(self.request(uri, 'POST', start_request, CONVERSATION_TYPE)) + + def conversation_update(self, id, update_request): + uri = CONVERSATION_PATH + '/' + str(id) + return Conversation().load(self.request(uri, 'PATCH', update_request, CONVERSATION_TYPE)) + + def conversation_read(self, id): + uri = CONVERSATION_PATH + '/' + str(id) + return Conversation().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) + + def conversation_list_messages(self, conversation_id, options=None): + uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH + + if options is not None: + uri += '?' + urlencode(options) + + return ConversationMessageList().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) + + def conversation_create_message(self, conversation_id, message_create_request): + uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH + return ConversationMessage().load(self.request(uri, 'POST', message_create_request, CONVERSATION_TYPE)) + + def conversation_read_message(self, message_id): + uri = CONVERSATION_MESSAGES_PATH + '/' + str(message_id) + return ConversationMessage().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) + + def conversation_create_webhook(self, webhook_create_request): + return ConversationWebhook().load(self.request(CONVERSATION_WEB_HOOKS_PATH, 'POST', webhook_create_request, CONVERSATION_TYPE)) + + def conversation_delete_webhook(self, id): + uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id) + self.request(uri, 'DELETE', None, CONVERSATION_TYPE) + + def conversation_list_webhooks(self, options=None): + uri = CONVERSATION_WEB_HOOKS_PATH + if options is not None: + uri += '?' + urlencode(options) + + return ConversationWebhookList().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) + + def conversation_read_webhook(self, id): + uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id) + return ConversationWebhook().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) diff --git a/messagebird/conversation_client.py b/messagebird/conversation_client.py deleted file mode 100644 index ebb2d93..0000000 --- a/messagebird/conversation_client.py +++ /dev/null @@ -1,80 +0,0 @@ -from messagebird.base import Base -from messagebird.client import USER_AGENT, Client -from messagebird.http_client import HttpClient -from messagebird.conversation_message import ConversationMessage, ConversationMessageList -from messagebird.conversation import Conversation, ConversationList -from messagebird.conversation_webhook import ConversationWebhook, ConversationWebhookList - -try: - from urllib.parse import urlencode -except ImportError: - from urllib import urlencode - -CONVERSATION_API_ROOT = 'https://conversations.messagebird.com/v1/' -CONVERSATION_PATH = 'conversations' -CONVERSATION_MESSAGES_PATH = 'messages' -CONVERSATION_WEB_HOOKS_PATH = 'webhooks' - - -class ConversationClient(Base): - - def __init__(self, access_key, http_client=None): - self.access_key = access_key - - if http_client is None: - http_client = HttpClient(CONVERSATION_API_ROOT, access_key, USER_AGENT) - - self.client = Client(access_key, http_client) - - def list(self, options=None): - uri = CONVERSATION_PATH - if options is not None: - uri += '?' + urlencode(options) - - return ConversationList().load(self.client.request(uri)) - - def start(self, start_request): - uri = CONVERSATION_PATH + '/start' - return Conversation().load(self.client.request(uri, 'POST', start_request)) - - def update(self, id, update_request): - uri = CONVERSATION_PATH + '/' + str(id) - return Conversation().load(self.client.request(uri, 'PATCH', update_request)) - - def read(self, id): - uri = CONVERSATION_PATH + '/' + str(id) - return Conversation().load(self.client.request(uri)) - - def list_messages(self, conversation_id, options=None): - uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH - - if options is not None: - uri += '?' + urlencode(options) - - return ConversationMessageList().load(self.client.request(uri)) - - def create_message(self, conversation_id, message_create_request): - uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH - return ConversationMessage().load(self.client.request(uri, 'POST', message_create_request)) - - def read_message(self, message_id): - uri = CONVERSATION_MESSAGES_PATH + '/' + str(message_id) - return ConversationMessage().load(self.client.request(uri)) - - def create_webhook(self, webhook_create_request): - return ConversationWebhook().load(self.client.request(CONVERSATION_WEB_HOOKS_PATH, 'POST', webhook_create_request)) - - def delete_webhook(self, id): - uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id) - self.client.request(uri, 'DELETE') - - def list_webhooks(self, options=None): - uri = CONVERSATION_WEB_HOOKS_PATH - if options is not None: - uri += '?' + urlencode(options) - - return ConversationWebhookList().load(self.client.request(uri)) - - def read_webhook(self, id): - uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id) - return ConversationWebhook().load(self.client.request(uri)) \ No newline at end of file diff --git a/tests/test_conversation.py b/tests/test_conversation.py index b97e479..4b91c12 100644 --- a/tests/test_conversation.py +++ b/tests/test_conversation.py @@ -1,6 +1,6 @@ import unittest from datetime import datetime -from messagebird import ConversationClient +from messagebird import Client try: from unittest.mock import Mock @@ -25,7 +25,7 @@ def test_conversation_start(self): }, } - msg = ConversationClient('', http_client).start(data) + msg = Client('', http_client).conversation_start(data) http_client.request.assert_called_once_with('conversations/start', 'POST', data) @@ -39,7 +39,7 @@ def test_conversation_list(self): http_client = Mock() http_client.request.return_value = '{}' - ConversationClient('', http_client).list() + Client('', http_client).conversation_list() http_client.request.assert_called_once_with('conversations', 'GET', None) @@ -47,7 +47,7 @@ def test_conversation_read(self): http_client = Mock() http_client.request.return_value = '{"id":"57b96dbe0fda40f0a814f5e3268c30a9","contactId":"8846d44229094c20813cf9eea596e680","contact":{"id":"8846d44229094c20813cf9eea596e680","href":"https://contacts.messagebird.com/v2/contacts/8846d44229094c20813cf9eea596e680","msisdn":31617110163,"displayName":"31617110163","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:54:39Z","updatedDatetime":"2019-04-02T08:54:40Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:54:38Z","updatedDatetime":"2019-04-02T14:24:09.192202886Z","lastReceivedDatetime":"2019-04-02T14:24:09.14826339Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":2,"href":"https://conversations.messagebird.com/v1/conversations/57b96dbe0fda40f0a814f5e3268c30a9/messages"}}' - conversation = ConversationClient('', http_client).read('conversation-id') + conversation = Client('', http_client).conversation_read('conversation-id') http_client.request.assert_called_once_with('conversations/conversation-id', 'GET', None) @@ -65,7 +65,7 @@ def test_conversation_update(self): updatedRequestData = {'status': 'archived'} - conversation = ConversationClient('', http_client).update('conversation-id', updatedRequestData) + conversation = Client('', http_client).conversation_update('conversation-id', updatedRequestData) http_client.request.assert_called_once_with('conversations/conversation-id', 'PATCH', updatedRequestData) self.assertEqual('archived', conversation.status) \ No newline at end of file diff --git a/tests/test_conversation_message.py b/tests/test_conversation_message.py index c6c096d..3800713 100644 --- a/tests/test_conversation_message.py +++ b/tests/test_conversation_message.py @@ -1,6 +1,6 @@ import unittest from datetime import datetime -from messagebird import ConversationClient +from messagebird import Client try: from unittest.mock import Mock @@ -16,7 +16,7 @@ def test_conversation_list_messages(self): http_client = Mock() http_client.request.return_value = '{"count":1,"items":[{"id":"54445534","conversationId":"54345543543","channelId":"4535434354","type":"text","content":{"text":"Hello"},"direction":"sent","status":"delivered","createdDatetime":"2019-04-02T08:54:54.608157775Z","updatedDatetime":"2019-04-02T08:54:54.63910221Z"}],"limit":10,"offset":0,"totalCount":1}' - msg = ConversationClient('', http_client).list_messages(54567) + msg = Client('', http_client).conversation_list_messages(54567) self.assertEqual(1, msg.count) self.assertEqual('54445534', msg.items[0].id) @@ -27,7 +27,7 @@ def test_conversation_read_message(self): http_client = Mock() http_client.request.return_value = '{}' - ConversationClient('', http_client).read_message('message-id') + Client('', http_client).conversation_read_message('message-id') http_client.request.assert_called_once_with('messages/message-id', 'GET', None) @@ -43,7 +43,7 @@ def test_create_message(self): }, } - msg = ConversationClient('', http_client).create_message('conversation-id', data) + msg = Client('', http_client).conversation_create_message('conversation-id', data) self.assertEqual(datetime(2019, 4, 2, 11, 57, 53), msg.updatedDatetime) self.assertEqual(datetime(2019, 4, 2, 11, 57, 52), msg.createdDatetime) diff --git a/tests/test_conversation_webhook.py b/tests/test_conversation_webhook.py index 5a04549..cc6ceb0 100644 --- a/tests/test_conversation_webhook.py +++ b/tests/test_conversation_webhook.py @@ -1,6 +1,6 @@ import unittest from datetime import datetime -from messagebird import ConversationClient +from messagebird import Client from messagebird.conversation_webhook import \ CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED,\ CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED @@ -25,7 +25,7 @@ def test_conversation_webhook_create(self): 'url': 'https://example.com' } - ConversationClient('', http_client).create_webhook(webhookRequestData) + Client('', http_client).conversation_create_webhook(webhookRequestData) http_client.request.assert_called_once_with('webhooks', 'POST', webhookRequestData) @@ -33,16 +33,15 @@ def test_conversation_webhook_delete(self): http_client = Mock() http_client.request.return_value = '' - ConversationClient('', http_client).delete_webhook('webhook-id') + Client('', http_client).conversation_delete_webhook('webhook-id') http_client.request.assert_called_once_with('webhooks/webhook-id', 'DELETE', None) - def test_conversation_webhook_list(self): http_client = Mock() http_client.request.return_value = '{"offset":0,"limit":10,"count":2,"totalCount":2,"items":[{"id":"57b96dbe0fda40f0a814f5e3268c30a9","contactId":"8846d44229094c20813cf9eea596e680","contact":{"id":"8846d44229094c20813cf9eea596e680","href":"https://contacts.messagebird.com/v2/contacts/8846d44229094c20813cf9eea596e680","msisdn":31617110163,"displayName":"31617110163","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:54:39Z","updatedDatetime":"2019-04-02T08:54:40Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:54:38Z","updatedDatetime":"2019-04-02T14:24:09.192202886Z","lastReceivedDatetime":"2019-04-02T14:24:09.14826339Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":2,"href":"https://conversations.messagebird.com/v1/conversations/57b96dbe0fda40f0a814f5e3268c30a9/messages"}},{"id":"07e823fdb36a462fb5e187d6d7b96493","contactId":"459a35432b0c4195abbdae353eb19359","contact":{"id":"459a35432b0c4195abbdae353eb19359","href":"https://contacts.messagebird.com/v2/contacts/459a35432b0c4195abbdae353eb19359","msisdn":31615164888,"displayName":"31615164888","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:19:38Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-03T07:35:47.35395356Z","lastReceivedDatetime":"2019-04-02T12:02:22.707634424Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":16,"href":"https://conversations.messagebird.com/v1/conversations/07e823fdb36a462fb5e187d6d7b96493/messages"}}]}' - ConversationClient('', http_client).list_webhooks() + Client('', http_client).conversation_list_webhooks() http_client.request.assert_called_once_with('webhooks', 'GET', None) def test_conversation_webhook_list_pagination(self): @@ -50,14 +49,14 @@ def test_conversation_webhook_list_pagination(self): http_client.request.return_value = '{"offset":0,"limit":10,"count":2,"totalCount":2,"items":[{"id":"57b96dbe0fda40f0a814f5e3268c30a9","contactId":"8846d44229094c20813cf9eea596e680","contact":{"id":"8846d44229094c20813cf9eea596e680","href":"https://contacts.messagebird.com/v2/contacts/8846d44229094c20813cf9eea596e680","msisdn":31617110163,"displayName":"31617110163","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:54:39Z","updatedDatetime":"2019-04-02T08:54:40Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:54:38Z","updatedDatetime":"2019-04-02T14:24:09.192202886Z","lastReceivedDatetime":"2019-04-02T14:24:09.14826339Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":2,"href":"https://conversations.messagebird.com/v1/conversations/57b96dbe0fda40f0a814f5e3268c30a9/messages"}},{"id":"07e823fdb36a462fb5e187d6d7b96493","contactId":"459a35432b0c4195abbdae353eb19359","contact":{"id":"459a35432b0c4195abbdae353eb19359","href":"https://contacts.messagebird.com/v2/contacts/459a35432b0c4195abbdae353eb19359","msisdn":31615164888,"displayName":"31615164888","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:19:38Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-03T07:35:47.35395356Z","lastReceivedDatetime":"2019-04-02T12:02:22.707634424Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":16,"href":"https://conversations.messagebird.com/v1/conversations/07e823fdb36a462fb5e187d6d7b96493/messages"}}]}' params = {'offset': 1, 'limit': 2} - ConversationClient('', http_client).list_webhooks(params) + Client('', http_client).conversation_list_webhooks(params) http_client.request.assert_called_once_with('webhooks?offset=1&limit=2', 'GET', None) def test_conversation_webhook_read(self): http_client = Mock() http_client.request.return_value = '{"id":"5031e2da142d401c93fbc38518ebb604","url":"https://example.com","channelId":"c0dae31e440145e094c4708b7d908842","events":["conversation.created","conversation.updated"],"status":"enabled","createdDatetime":"2019-04-03T08:41:37Z","updatedDatetime":null}' - webhook = ConversationClient('', http_client).read_webhook('webhook-id') + webhook = Client('', http_client).conversation_read_webhook('webhook-id') http_client.request.assert_called_once_with('webhooks/webhook-id', 'GET', None) self.assertEqual(datetime(2019, 4, 3, 8, 41, 37), webhook.createdDatetime) From fb947c2c16d6dce719ed083dcc014b5d5100e576 Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Wed, 3 Apr 2019 11:19:53 +0200 Subject: [PATCH 12/16] Update list methods to receive limit and offset by parameter --- messagebird/client.py | 37 +++++++++++------------------- tests/test_conversation.py | 2 +- tests/test_conversation_message.py | 2 +- tests/test_conversation_webhook.py | 7 +++--- 4 files changed, 19 insertions(+), 29 deletions(-) diff --git a/messagebird/client.py b/messagebird/client.py index 34dc464..0360bd2 100644 --- a/messagebird/client.py +++ b/messagebird/client.py @@ -15,11 +15,6 @@ from messagebird.conversation import Conversation, ConversationList from messagebird.conversation_webhook import ConversationWebhook, ConversationWebhookList -try: - from urllib.parse import urlencode -except ImportError: - from urllib import urlencode - ENDPOINT = 'https://rest.messagebird.com' CLIENT_VERSION = '1.3.1' PYTHON_VERSION = '%d.%d.%d' % (sys.version_info[0], sys.version_info[1], sys.version_info[2]) @@ -45,7 +40,7 @@ def __init__(self, access_key, http_client=None): self.access_key = access_key self.http_client = http_client - def getHttpClient(self, type=REST_TYPE): + def _get_http_client(self, type=REST_TYPE): if self.http_client: return self.http_client @@ -56,7 +51,7 @@ def getHttpClient(self, type=REST_TYPE): def request(self, path, method='GET', params=None, type=REST_TYPE): """Builds a request, gets a response and decodes it.""" - response_text = self.getHttpClient(type).request(path, method, params) + response_text = self._get_http_client(type).request(path, method, params) if not response_text: return response_text @@ -70,7 +65,7 @@ def request(self, path, method='GET', params=None, type=REST_TYPE): def request_plain_text(self, path, method='GET', params=None, type=REST_TYPE): """Builds a request, gets a response and returns the body.""" - response_text = self.getHttpClient(type).request(path, method, params) + response_text = self._get_http_client(type).request(path, method, params) try: # Try to decode the response to JSON to see if the API returned any @@ -173,7 +168,7 @@ def contact_update(self, id, params=None): self.request_plain_text('contacts/' + str(id), 'PATCH', params) def contact_list(self, limit=10, offset=0): - query = 'limit='+str(limit)+'&offset='+str(offset) + query = self._format_query(limit, offset) return ContactList().load(self.request('contacts?'+query, 'GET', None)) def group(self, id): @@ -188,7 +183,7 @@ def group_delete(self, id): self.request_plain_text('groups/' + str(id), 'DELETE', None) def group_list(self, limit=10, offset=0): - query = 'limit=' + str(limit) + '&offset=' + str(offset) + query = self._format_query(limit, offset) return GroupList().load(self.request('groups?'+query, 'GET', None)) def group_update(self, id, name, params=None): @@ -209,11 +204,8 @@ def __group_add_contacts_query(self, contactIds): def group_remove_contact(self, groupId, contactId): self.request_plain_text('groups/' + str(groupId) + '/contacts/' + str(contactId), 'DELETE', None) - def conversation_list(self, options=None): - uri = CONVERSATION_PATH - if options is not None: - uri += '?' + urlencode(options) - + def conversation_list(self, limit=10, offset=0): + uri = CONVERSATION_PATH + '?' + self._format_query(limit, offset) return ConversationList().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) def conversation_start(self, start_request): @@ -228,11 +220,9 @@ def conversation_read(self, id): uri = CONVERSATION_PATH + '/' + str(id) return Conversation().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) - def conversation_list_messages(self, conversation_id, options=None): + def conversation_list_messages(self, conversation_id, limit=10, offset=0): uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH - - if options is not None: - uri += '?' + urlencode(options) + uri += '?' + self._format_query(limit, offset) return ConversationMessageList().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) @@ -251,13 +241,14 @@ def conversation_delete_webhook(self, id): uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id) self.request(uri, 'DELETE', None, CONVERSATION_TYPE) - def conversation_list_webhooks(self, options=None): - uri = CONVERSATION_WEB_HOOKS_PATH - if options is not None: - uri += '?' + urlencode(options) + def conversation_list_webhooks(self, limit=10, offset=0): + uri = CONVERSATION_WEB_HOOKS_PATH + '?' + self._format_query(limit, offset) return ConversationWebhookList().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) def conversation_read_webhook(self, id): uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id) return ConversationWebhook().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) + + def _format_query(self, limit, offset): + return 'limit='+str(limit)+'&offset='+str(offset) diff --git a/tests/test_conversation.py b/tests/test_conversation.py index 4b91c12..8ea30bd 100644 --- a/tests/test_conversation.py +++ b/tests/test_conversation.py @@ -41,7 +41,7 @@ def test_conversation_list(self): Client('', http_client).conversation_list() - http_client.request.assert_called_once_with('conversations', 'GET', None) + http_client.request.assert_called_once_with('conversations?limit=10&offset=0', 'GET', None) def test_conversation_read(self): http_client = Mock() diff --git a/tests/test_conversation_message.py b/tests/test_conversation_message.py index 3800713..47e9f3c 100644 --- a/tests/test_conversation_message.py +++ b/tests/test_conversation_message.py @@ -21,7 +21,7 @@ def test_conversation_list_messages(self): self.assertEqual(1, msg.count) self.assertEqual('54445534', msg.items[0].id) - http_client.request.assert_called_once_with('conversations/54567/messages', 'GET', None) + http_client.request.assert_called_once_with('conversations/54567/messages?limit=10&offset=0', 'GET', None) def test_conversation_read_message(self): http_client = Mock() diff --git a/tests/test_conversation_webhook.py b/tests/test_conversation_webhook.py index cc6ceb0..85a6fd9 100644 --- a/tests/test_conversation_webhook.py +++ b/tests/test_conversation_webhook.py @@ -42,15 +42,14 @@ def test_conversation_webhook_list(self): http_client.request.return_value = '{"offset":0,"limit":10,"count":2,"totalCount":2,"items":[{"id":"57b96dbe0fda40f0a814f5e3268c30a9","contactId":"8846d44229094c20813cf9eea596e680","contact":{"id":"8846d44229094c20813cf9eea596e680","href":"https://contacts.messagebird.com/v2/contacts/8846d44229094c20813cf9eea596e680","msisdn":31617110163,"displayName":"31617110163","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:54:39Z","updatedDatetime":"2019-04-02T08:54:40Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:54:38Z","updatedDatetime":"2019-04-02T14:24:09.192202886Z","lastReceivedDatetime":"2019-04-02T14:24:09.14826339Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":2,"href":"https://conversations.messagebird.com/v1/conversations/57b96dbe0fda40f0a814f5e3268c30a9/messages"}},{"id":"07e823fdb36a462fb5e187d6d7b96493","contactId":"459a35432b0c4195abbdae353eb19359","contact":{"id":"459a35432b0c4195abbdae353eb19359","href":"https://contacts.messagebird.com/v2/contacts/459a35432b0c4195abbdae353eb19359","msisdn":31615164888,"displayName":"31615164888","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:19:38Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-03T07:35:47.35395356Z","lastReceivedDatetime":"2019-04-02T12:02:22.707634424Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":16,"href":"https://conversations.messagebird.com/v1/conversations/07e823fdb36a462fb5e187d6d7b96493/messages"}}]}' Client('', http_client).conversation_list_webhooks() - http_client.request.assert_called_once_with('webhooks', 'GET', None) + http_client.request.assert_called_once_with('webhooks?limit=10&offset=0', 'GET', None) def test_conversation_webhook_list_pagination(self): http_client = Mock() http_client.request.return_value = '{"offset":0,"limit":10,"count":2,"totalCount":2,"items":[{"id":"57b96dbe0fda40f0a814f5e3268c30a9","contactId":"8846d44229094c20813cf9eea596e680","contact":{"id":"8846d44229094c20813cf9eea596e680","href":"https://contacts.messagebird.com/v2/contacts/8846d44229094c20813cf9eea596e680","msisdn":31617110163,"displayName":"31617110163","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:54:39Z","updatedDatetime":"2019-04-02T08:54:40Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:54:38Z","updatedDatetime":"2019-04-02T14:24:09.192202886Z","lastReceivedDatetime":"2019-04-02T14:24:09.14826339Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":2,"href":"https://conversations.messagebird.com/v1/conversations/57b96dbe0fda40f0a814f5e3268c30a9/messages"}},{"id":"07e823fdb36a462fb5e187d6d7b96493","contactId":"459a35432b0c4195abbdae353eb19359","contact":{"id":"459a35432b0c4195abbdae353eb19359","href":"https://contacts.messagebird.com/v2/contacts/459a35432b0c4195abbdae353eb19359","msisdn":31615164888,"displayName":"31615164888","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:19:38Z"},"channels":[{"id":"c0dae31e440145e094c4708b7d908842","name":"test","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-03T07:35:47.35395356Z","lastReceivedDatetime":"2019-04-02T12:02:22.707634424Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":16,"href":"https://conversations.messagebird.com/v1/conversations/07e823fdb36a462fb5e187d6d7b96493/messages"}}]}' - params = {'offset': 1, 'limit': 2} - Client('', http_client).conversation_list_webhooks(params) - http_client.request.assert_called_once_with('webhooks?offset=1&limit=2', 'GET', None) + Client('', http_client).conversation_list_webhooks(2, 1) + http_client.request.assert_called_once_with('webhooks?limit=2&offset=1', 'GET', None) def test_conversation_webhook_read(self): http_client = Mock() From bdc3e3f3eb93c07283f13a643dff1699d9805a83 Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Fri, 5 Apr 2019 10:00:48 +0200 Subject: [PATCH 13/16] Update examples to receive arguments instead of hardcoded constants --- examples/conversation_create_message.py | 44 ++++++------------------- examples/conversation_create_webhook.py | 31 ++++++----------- examples/conversation_delete_webhook.py | 28 +++++----------- examples/conversation_list.py | 20 ++++------- examples/conversation_list_messages.py | 28 +++++----------- examples/conversation_list_webhook.py | 18 ++++------ examples/conversation_read.py | 28 +++++----------- examples/conversation_read_message.py | 29 +++++----------- examples/conversation_read_webhook.py | 28 +++++----------- examples/conversation_start.py | 44 ++++++------------------- examples/conversation_update.py | 28 +++++----------- 11 files changed, 91 insertions(+), 235 deletions(-) diff --git a/examples/conversation_create_message.py b/examples/conversation_create_message.py index a586503..aa7bf9b 100644 --- a/examples/conversation_create_message.py +++ b/examples/conversation_create_message.py @@ -1,44 +1,20 @@ #!/usr/bin/env python - -import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) - +import sys +import argparse import messagebird from messagebird.conversation_message import MESSAGE_TYPE_TEXT -# ACCESS_KEY = '' -# CONVERSATION_ID = '' -# CHANNEL_ID = '' -# TEXT_MESSAGE = '' - -try: - ACCESS_KEY -except NameError: - print('You need to set an ACCESS_KEY constant in this file') - sys.exit(1) - -try: - CONVERSATION_ID -except NameError: - print('You need to set a CONVERSATION_ID constant in this file') - sys.exit(1) - -try: - CHANNEL_ID -except NameError: - print('You need to set a CHANNEL_ID constant in this file') - sys.exit(1) - -try: - TEXT_MESSAGE -except NameError: - print('You need to set a TEXT_MESSAGE constant in this file') - sys.exit(1) +parser = argparse.ArgumentParser() +parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) +parser.add_argument('--conversationId', help='conversation ID that you want to create a message for', type=str, required=True) +parser.add_argument('--channelId', help='channel ID that you want to create a message for', type=str, required=True) +parser.add_argument('--message', help='message that you want to send', type=str, required=True) +args = vars(parser.parse_args()) try: - client = messagebird.Client(ACCESS_KEY) + client = messagebird.Client(args['accessKey']) - msg = client.conversation_create_message(CONVERSATION_ID, { 'channelId': CHANNEL_ID, 'type': MESSAGE_TYPE_TEXT, 'content': { 'text': TEXT_MESSAGE } }) + msg = client.conversation_create_message(args['conversationId'], { 'channelId': args['channelId'], 'type': MESSAGE_TYPE_TEXT, 'content': { 'text': args['message'] } }) # Print the object information. print('\nThe following information was returned as a Conversation List object:\n') diff --git a/examples/conversation_create_webhook.py b/examples/conversation_create_webhook.py index b94b1e9..3af60b7 100644 --- a/examples/conversation_create_webhook.py +++ b/examples/conversation_create_webhook.py @@ -1,35 +1,24 @@ #!/usr/bin/env python - -import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) - +import sys +import argparse import messagebird from messagebird.conversation_webhook import \ CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED,\ CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED -# ACCESS_KEY = '' -# CHANNEL_ID = '' - -try: - ACCESS_KEY -except NameError: - print('You need to set an ACCESS_KEY constant in this file') - sys.exit(1) - -try: - CHANNEL_ID -except NameError: - print('You need to set an CHANNEL_ID constant in this file') - sys.exit(1) +parser = argparse.ArgumentParser() +parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) +parser.add_argument('--channelId', help='channel that you want create the webhook', type=str, required=True) +parser.add_argument('--url', help='url for the webhook', type=str) +args = vars(parser.parse_args()) try: - client = messagebird.Client(ACCESS_KEY) + client = messagebird.Client(args['accessKey']) webhook = client.conversation_create_webhook({ - 'channelId': CHANNEL_ID, + 'channelId': args['channelId'], 'events': [CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED, CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED], - 'url': 'https://example.com' + 'url': args['url'] }) # Print the object information. diff --git a/examples/conversation_delete_webhook.py b/examples/conversation_delete_webhook.py index f7f6374..877c088 100644 --- a/examples/conversation_delete_webhook.py +++ b/examples/conversation_delete_webhook.py @@ -1,29 +1,17 @@ #!/usr/bin/env python - -import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) - +import sys +import argparse import messagebird -# ACCESS_KEY = '' -# WEBHOOK_ID = '' - -try: - ACCESS_KEY -except NameError: - print('You need to set an ACCESS_KEY constant in this file') - sys.exit(1) - -try: - WEBHOOK_ID -except NameError: - print('You need to set an WEBHOOK_ID constant in this file') - sys.exit(1) +parser = argparse.ArgumentParser() +parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) +parser.add_argument('--webhookId', help='webhook that you want to delete', type=str, required=True) +args = vars(parser.parse_args()) try: - client = messagebird.Client(ACCESS_KEY) + client = messagebird.Client(args['accessKey']) - client.conversation_delete_webhook(WEBHOOK_ID) + client.conversation_delete_webhook(args['webhookId']) # Print the object information. print('\nWebhook has been deleted:\n') diff --git a/examples/conversation_list.py b/examples/conversation_list.py index 40dbde7..57bf4cd 100644 --- a/examples/conversation_list.py +++ b/examples/conversation_list.py @@ -1,20 +1,14 @@ #!/usr/bin/env python - -import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) - import messagebird +import argparse +import sys -# ACCESS_KEY = '' - -try: - ACCESS_KEY -except NameError: - print('You need to set an ACCESS_KEY constant in this file') - sys.exit(1) +parser = argparse.ArgumentParser() +parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) +args = vars(parser.parse_args()) try: - client = messagebird.Client(ACCESS_KEY) + client = messagebird.Client(args['accessKey']) conversationList = client.conversation_list() @@ -35,4 +29,4 @@ for error in e.errors: print(' code : %d' % error.code) print(' description : %s' % error.description) - print(' parameter : %s\n' % error.parameter) \ No newline at end of file + print(' parameter : %s\n' % error.parameter) diff --git a/examples/conversation_list_messages.py b/examples/conversation_list_messages.py index 7ff5f44..999294d 100644 --- a/examples/conversation_list_messages.py +++ b/examples/conversation_list_messages.py @@ -1,29 +1,17 @@ #!/usr/bin/env python - -import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) - +import sys +import argparse import messagebird -# ACCESS_KEY = '' -# CONVERSATION_ID = '' - -try: - ACCESS_KEY -except NameError: - print('You need to set an ACCESS_KEY constant in this file') - sys.exit(1) - -try: - CONVERSATION_ID -except NameError: - print('You need to set a CONVERSATION_ID constant in this file') - sys.exit(1) +parser = argparse.ArgumentParser() +parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) +parser.add_argument('--conversationId', help='conversation that you want the list of messages', type=str, required=True) +args = vars(parser.parse_args()) try: - client = messagebird.Client(ACCESS_KEY) + client = messagebird.Client(args['accessKey']) - msg = client.conversation_list_messages(CONVERSATION_ID) + msg = client.conversation_list_messages(args['conversationId']) itemIds = [] for msgItem in msg.items: diff --git a/examples/conversation_list_webhook.py b/examples/conversation_list_webhook.py index 453127a..30f1b92 100644 --- a/examples/conversation_list_webhook.py +++ b/examples/conversation_list_webhook.py @@ -1,20 +1,14 @@ #!/usr/bin/env python - -import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) - +import sys +import argparse import messagebird -# ACCESS_KEY = '' - -try: - ACCESS_KEY -except NameError: - print('You need to set an ACCESS_KEY constant in this file') - sys.exit(1) +parser = argparse.ArgumentParser() +parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) +args = vars(parser.parse_args()) try: - client = messagebird.Client(ACCESS_KEY) + client = messagebird.Client(args['accessKey']) webhookList = client.conversation_list_webhooks() diff --git a/examples/conversation_read.py b/examples/conversation_read.py index 5ff1e0f..cd27b61 100644 --- a/examples/conversation_read.py +++ b/examples/conversation_read.py @@ -1,29 +1,17 @@ #!/usr/bin/env python - -import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) - import messagebird +import argparse +import sys -# ACCESS_KEY = '' -# CONVERSATION_ID = '' - -try: - ACCESS_KEY -except NameError: - print('You need to set an ACCESS_KEY constant in this file') - sys.exit(1) - -try: - CONVERSATION_ID -except NameError: - print('You need to set an CONVERSATION_ID constant in this file') - sys.exit(1) +parser = argparse.ArgumentParser() +parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) +parser.add_argument('--conversationId', help='conversation that you want the message list', type=str, required=True) +args = vars(parser.parse_args()) try: - client = messagebird.Client(ACCESS_KEY) + client = messagebird.Client(args['accessKey']) - conversation = client.conversation_read(CONVERSATION_ID) + conversation = client.conversation_read(args['conversationId']) # Print the object information. print('\nThe following information was returned as a Conversation object:\n') diff --git a/examples/conversation_read_message.py b/examples/conversation_read_message.py index 87cbced..c55caf8 100644 --- a/examples/conversation_read_message.py +++ b/examples/conversation_read_message.py @@ -1,30 +1,17 @@ #!/usr/bin/env python - -import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) - +import sys +import argparse import messagebird -# ACCESS_KEY = '' -# MESSAGE_ID = '' - -try: - ACCESS_KEY -except NameError: - print('You need to set an ACCESS_KEY constant in this file') - sys.exit(1) - -try: - MESSAGE_ID -except NameError: - print('You need to set a MESSAGE_ID constant in this file') - sys.exit(1) - +parser = argparse.ArgumentParser() +parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) +parser.add_argument('--messageId', help='message that you want to read', type=str, required=True) +args = vars(parser.parse_args()) try: - client = messagebird.Client(ACCESS_KEY) + client = messagebird.Client(args['accessKey']) - msg = client.conversation_read_message(MESSAGE_ID) + msg = client.conversation_read_message(args['messageId']) # Print the object information. print('\nThe following information was returned as a Conversation List object:\n') diff --git a/examples/conversation_read_webhook.py b/examples/conversation_read_webhook.py index 9d62430..6a1b8e0 100644 --- a/examples/conversation_read_webhook.py +++ b/examples/conversation_read_webhook.py @@ -1,29 +1,17 @@ #!/usr/bin/env python - -import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) - +import sys import messagebird +import argparse -# ACCESS_KEY = '' -# WEBHOOK_ID = '' - -try: - ACCESS_KEY -except NameError: - print('You need to set an ACCESS_KEY constant in this file') - sys.exit(1) - -try: - WEBHOOK_ID -except NameError: - print('You need to set an WEBHOOK_ID constant in this file') - sys.exit(1) +parser = argparse.ArgumentParser() +parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) +parser.add_argument('--webhookId', help='webhook that you want to read', type=str, required=True) +args = vars(parser.parse_args()) try: - client = messagebird.Client(ACCESS_KEY) + client = messagebird.Client(args['accessKey']) - webhook = client.conversation_read_webhook(WEBHOOK_ID) + webhook = client.conversation_read_webhook(args['webhookId']) # Print the object information. print('\nThe following information was returned as a Webhook object:\n') diff --git a/examples/conversation_start.py b/examples/conversation_start.py index 8e91d9a..85e1968 100644 --- a/examples/conversation_start.py +++ b/examples/conversation_start.py @@ -1,44 +1,20 @@ #!/usr/bin/env python - -import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) - +import sys +import argparse import messagebird from messagebird.conversation_message import MESSAGE_TYPE_TEXT -# ACCESS_KEY = '' -# CHANNEL_ID = '' -# PHONE_NUMBER = '' -# TEXT_MESSAGE = '' - -try: - ACCESS_KEY -except NameError: - print('You need to set an ACCESS_KEY constant in this file') - sys.exit(1) - -try: - CHANNEL_ID -except NameError: - print('You need to set a CHANNEL_ID constant in this file') - sys.exit(1) - -try: - PHONE_NUMBER -except NameError: - print('You need to set a PHONE_NUMBEr constant in this file') - sys.exit(1) - -try: - TEXT_NUMBER -except NameError: - print('You need to set a TEXT_NUMBER constant in this file') - sys.exit(1) +parser = argparse.ArgumentParser() +parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) +parser.add_argument('--channelId', help='channel that you want to start a conversation', type=str, required=True) +parser.add_argument('--phoneNumber', help='phone number that you want to send a message', type=str, required=True) +parser.add_argument('--textMessage', help='text that you want to send', type=str, required=True) +args = vars(parser.parse_args()) try: - client = messagebird.Client(ACCESS_KEY) + client = messagebird.Client(args['accessKey']) - msg = client.conversation_start({ 'channelId': CHANNEL_ID, 'to': PHONE_NUMBER, 'type': MESSAGE_TYPE_TEXT, 'content': { 'text': TEXT_MESSAGE } }) + msg = client.conversation_start({ 'channelId': args['channelId'], 'to': args['phoneNumber'], 'type': MESSAGE_TYPE_TEXT, 'content': { 'text': args['textMessage'] } }) # Print the object information. print('\nThe following information was returned as a Conversation object:\n') diff --git a/examples/conversation_update.py b/examples/conversation_update.py index ef9996d..7ad15e3 100644 --- a/examples/conversation_update.py +++ b/examples/conversation_update.py @@ -1,29 +1,17 @@ #!/usr/bin/env python - -import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) - +import sys +import argparse import messagebird -# ACCESS_KEY = '' -# CONVERSATION_ID = '' - -try: - ACCESS_KEY -except NameError: - print('You need to set an ACCESS_KEY constant in this file') - sys.exit(1) - -try: - CONVERSATION_ID -except NameError: - print('You need to set an CONVERSATION_ID constant in this file') - sys.exit(1) +parser = argparse.ArgumentParser() +parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) +parser.add_argument('--conversationId', help='conversation ID that you want to update', type=str, required=True) +args = vars(parser.parse_args()) try: - client = messagebird.Client(ACCESS_KEY) + client = messagebird.Client(args['accessKey']) - conversation = client.conversation_update(CONVERSATION_ID, {'status': 'active'}) + conversation = client.conversation_update(args['conversationId'], {'status': 'active'}) # Print the object information. print('\nThe following information was returned as a Conversation object:\n') From bb53bab200f981db97487fa400d127ecac372758 Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Mon, 8 Apr 2019 10:04:27 +0200 Subject: [PATCH 14/16] Format code properly --- examples/conversation_create_message.py | 42 +-- examples/conversation_create_webhook.py | 39 ++- examples/conversation_delete_webhook.py | 19 +- examples/conversation_list.py | 33 +- examples/conversation_list_messages.py | 33 +- examples/conversation_list_webhook.py | 33 +- examples/conversation_read.py | 33 +- examples/conversation_read_message.py | 37 ++- examples/conversation_read_webhook.py | 29 +- examples/conversation_start.py | 41 +-- examples/conversation_update.py | 33 +- messagebird/client.py | 383 ++++++++++++------------ messagebird/conversation_channel.py | 3 +- messagebird/conversation_contact.py | 2 +- tests/test_conversation.py | 10 +- tests/test_conversation_message.py | 4 +- tests/test_conversation_webhook.py | 17 +- 17 files changed, 394 insertions(+), 397 deletions(-) diff --git a/examples/conversation_create_message.py b/examples/conversation_create_message.py index aa7bf9b..5e50ef0 100644 --- a/examples/conversation_create_message.py +++ b/examples/conversation_create_message.py @@ -1,37 +1,39 @@ #!/usr/bin/env python -import sys import argparse import messagebird from messagebird.conversation_message import MESSAGE_TYPE_TEXT parser = argparse.ArgumentParser() parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) -parser.add_argument('--conversationId', help='conversation ID that you want to create a message for', type=str, required=True) +parser.add_argument('--conversationId', help='conversation ID that you want to create a message for', type=str, + required=True) parser.add_argument('--channelId', help='channel ID that you want to create a message for', type=str, required=True) parser.add_argument('--message', help='message that you want to send', type=str, required=True) args = vars(parser.parse_args()) try: - client = messagebird.Client(args['accessKey']) + client = messagebird.Client(args['accessKey']) - msg = client.conversation_create_message(args['conversationId'], { 'channelId': args['channelId'], 'type': MESSAGE_TYPE_TEXT, 'content': { 'text': args['message'] } }) + msg = client.conversation_create_message(args['conversationId'], + {'channelId': args['channelId'], 'type': MESSAGE_TYPE_TEXT, + 'content': {'text': args['message']}}) - # Print the object information. - print('\nThe following information was returned as a Conversation List object:\n') - print(' message id : %s' % msg.id) - print(' channel id : %s' % msg.channelId) - print(' direction : %s' % msg.direction) - print(' content : %s' % msg.content) - print(' content : %s' % msg.content) - print(' status : %s' % msg.status) - print(' type : %s' % msg.type) - print(' created date : %s' % msg.createdDatetime) - print(' updated date : %s' % msg.updatedDatetime) + # Print the object information. + print('\nThe following information was returned as a Conversation List object:\n') + print(' message id : %s' % msg.id) + print(' channel id : %s' % msg.channelId) + print(' direction : %s' % msg.direction) + print(' content : %s' % msg.content) + print(' content : %s' % msg.content) + print(' status : %s' % msg.status) + print(' type : %s' % msg.type) + print(' created date : %s' % msg.createdDatetime) + print(' updated date : %s' % msg.updatedDatetime) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Message object:\n') + print('\nAn error occured while requesting a Message object:\n') - for error in e.errors: - print(' code : %d' % error.code) - print(' description : %s' % error.description) - print(' parameter : %s\n' % error.parameter) + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/examples/conversation_create_webhook.py b/examples/conversation_create_webhook.py index 3af60b7..5b171ba 100644 --- a/examples/conversation_create_webhook.py +++ b/examples/conversation_create_webhook.py @@ -1,9 +1,8 @@ #!/usr/bin/env python -import sys import argparse import messagebird from messagebird.conversation_webhook import \ - CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED,\ + CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED, \ CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED parser = argparse.ArgumentParser() @@ -13,26 +12,26 @@ args = vars(parser.parse_args()) try: - client = messagebird.Client(args['accessKey']) + client = messagebird.Client(args['accessKey']) - webhook = client.conversation_create_webhook({ - 'channelId': args['channelId'], - 'events': [CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED, CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED], - 'url': args['url'] - }) + webhook = client.conversation_create_webhook({ + 'channelId': args['channelId'], + 'events': [CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED, CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED], + 'url': args['url'] + }) - # Print the object information. - print('\nThe following information was returned as a Webhook object:\n') - print(' id : %s' % webhook.id) - print(' events : %s' % webhook.events) - print(' channel id : %s' % webhook.channelId) - print(' created date : %s' % webhook.createdDatetime) - print(' updated date : %s' % webhook.updatedDatetime) + # Print the object information. + print('\nThe following information was returned as a Webhook object:\n') + print(' id : %s' % webhook.id) + print(' events : %s' % webhook.events) + print(' channel id : %s' % webhook.channelId) + print(' created date : %s' % webhook.createdDatetime) + print(' updated date : %s' % webhook.updatedDatetime) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Webhook object:\n') + print('\nAn error occured while requesting a Webhook object:\n') - for error in e.errors: - print(' code : %d' % error.code) - print(' description : %s' % error.description) - print(' parameter : %s\n' % error.parameter) \ No newline at end of file + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/examples/conversation_delete_webhook.py b/examples/conversation_delete_webhook.py index 877c088..4f65211 100644 --- a/examples/conversation_delete_webhook.py +++ b/examples/conversation_delete_webhook.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import sys import argparse import messagebird @@ -9,17 +8,17 @@ args = vars(parser.parse_args()) try: - client = messagebird.Client(args['accessKey']) + client = messagebird.Client(args['accessKey']) - client.conversation_delete_webhook(args['webhookId']) + client.conversation_delete_webhook(args['webhookId']) - # Print the object information. - print('\nWebhook has been deleted:\n') + # Print the object information. + print('\nWebhook has been deleted:\n') except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Webhook object:\n') + print('\nAn error occured while requesting a Webhook object:\n') - for error in e.errors: - print(' code : %d' % error.code) - print(' description : %s' % error.description) - print(' parameter : %s\n' % error.parameter) \ No newline at end of file + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/examples/conversation_list.py b/examples/conversation_list.py index 57bf4cd..236c596 100644 --- a/examples/conversation_list.py +++ b/examples/conversation_list.py @@ -1,32 +1,31 @@ #!/usr/bin/env python import messagebird import argparse -import sys parser = argparse.ArgumentParser() parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) args = vars(parser.parse_args()) try: - client = messagebird.Client(args['accessKey']) + client = messagebird.Client(args['accessKey']) - conversationList = client.conversation_list() + conversationList = client.conversation_list() - itemIds = [] - for msgItem in conversationList.items: - itemIds.append(msgItem.id) + itemIds = [] + for msgItem in conversationList.items: + itemIds.append(msgItem.id) - # Print the object information. - print('\nThe following information was returned as a Conversation List object:\n') - print(' conversation ids : %s' % itemIds) - print(' offset : %s' % conversationList.offset) - print(' limit : %s' % conversationList.limit) - print(' totalCount : %s' % conversationList.totalCount) + # Print the object information. + print('\nThe following information was returned as a Conversation List object:\n') + print(' conversation ids : %s' % itemIds) + print(' offset : %s' % conversationList.offset) + print(' limit : %s' % conversationList.limit) + print(' totalCount : %s' % conversationList.totalCount) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Message object:\n') + print('\nAn error occured while requesting a Message object:\n') - for error in e.errors: - print(' code : %d' % error.code) - print(' description : %s' % error.description) - print(' parameter : %s\n' % error.parameter) + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/examples/conversation_list_messages.py b/examples/conversation_list_messages.py index 999294d..7fb3d12 100644 --- a/examples/conversation_list_messages.py +++ b/examples/conversation_list_messages.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import sys import argparse import messagebird @@ -9,25 +8,25 @@ args = vars(parser.parse_args()) try: - client = messagebird.Client(args['accessKey']) + client = messagebird.Client(args['accessKey']) - msg = client.conversation_list_messages(args['conversationId']) + msg = client.conversation_list_messages(args['conversationId']) - itemIds = [] - for msgItem in msg.items: - itemIds.append(msgItem.id) + itemIds = [] + for msgItem in msg.items: + itemIds.append(msgItem.id) - # Print the object information. - print('\nThe following information was returned as a Conversation Message List object:\n') - print(' message ids : %s' % itemIds) - print(' offset : %s' % msg.offset) - print(' limit : %s' % msg.limit) - print(' totalCount : %s' % msg.totalCount) + # Print the object information. + print('\nThe following information was returned as a Conversation Message List object:\n') + print(' message ids : %s' % itemIds) + print(' offset : %s' % msg.offset) + print(' limit : %s' % msg.limit) + print(' totalCount : %s' % msg.totalCount) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Conversation Message List object:\n') + print('\nAn error occured while requesting a Conversation Message List object:\n') - for error in e.errors: - print(' code : %d' % error.code) - print(' description : %s' % error.description) - print(' parameter : %s\n' % error.parameter) + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/examples/conversation_list_webhook.py b/examples/conversation_list_webhook.py index 30f1b92..d0cdd28 100644 --- a/examples/conversation_list_webhook.py +++ b/examples/conversation_list_webhook.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import sys import argparse import messagebird @@ -8,25 +7,25 @@ args = vars(parser.parse_args()) try: - client = messagebird.Client(args['accessKey']) + client = messagebird.Client(args['accessKey']) - webhookList = client.conversation_list_webhooks() + webhookList = client.conversation_list_webhooks() - itemIds = [] - for msgItem in webhookList.items: - itemIds.append(msgItem.id) + itemIds = [] + for msgItem in webhookList.items: + itemIds.append(msgItem.id) - # Print the object information. - print('\nThe following information was returned as a Conversation Webhook List object:\n') - print(' conversation ids : %s' % itemIds) - print(' offset : %s' % webhookList.offset) - print(' limit : %s' % webhookList.limit) - print(' totalCount : %s' % webhookList.totalCount) + # Print the object information. + print('\nThe following information was returned as a Conversation Webhook List object:\n') + print(' conversation ids : %s' % itemIds) + print(' offset : %s' % webhookList.offset) + print(' limit : %s' % webhookList.limit) + print(' totalCount : %s' % webhookList.totalCount) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Conversation Webhook List object:\n') + print('\nAn error occured while requesting a Conversation Webhook List object:\n') - for error in e.errors: - print(' code : %d' % error.code) - print(' description : %s' % error.description) - print(' parameter : %s\n' % error.parameter) \ No newline at end of file + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/examples/conversation_read.py b/examples/conversation_read.py index cd27b61..d817ff1 100644 --- a/examples/conversation_read.py +++ b/examples/conversation_read.py @@ -1,7 +1,6 @@ #!/usr/bin/env python import messagebird import argparse -import sys parser = argparse.ArgumentParser() parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) @@ -9,24 +8,24 @@ args = vars(parser.parse_args()) try: - client = messagebird.Client(args['accessKey']) + client = messagebird.Client(args['accessKey']) - conversation = client.conversation_read(args['conversationId']) + conversation = client.conversation_read(args['conversationId']) - # Print the object information. - print('\nThe following information was returned as a Conversation object:\n') - print(' conversation id : %s' % conversation.id) - print(' contact id : %s' % conversation.contactId) - print(' messages total count : %s' % conversation.messages.totalCount) - print(' status : %s' % conversation.status) - print(' created date time : %s' % conversation.createdDatetime) - print(' updated date time : %s' % conversation.updatedDatetime) - print(' last received date time : %s' % conversation.lastReceivedDatetime) + # Print the object information. + print('\nThe following information was returned as a Conversation object:\n') + print(' conversation id : %s' % conversation.id) + print(' contact id : %s' % conversation.contactId) + print(' messages total count : %s' % conversation.messages.totalCount) + print(' status : %s' % conversation.status) + print(' created date time : %s' % conversation.createdDatetime) + print(' updated date time : %s' % conversation.updatedDatetime) + print(' last received date time : %s' % conversation.lastReceivedDatetime) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Conversation object:\n') + print('\nAn error occured while requesting a Conversation object:\n') - for error in e.errors: - print(' code : %d' % error.code) - print(' description : %s' % error.description) - print(' parameter : %s\n' % error.parameter) \ No newline at end of file + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/examples/conversation_read_message.py b/examples/conversation_read_message.py index c55caf8..3f9371b 100644 --- a/examples/conversation_read_message.py +++ b/examples/conversation_read_message.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import sys import argparse import messagebird @@ -9,26 +8,26 @@ args = vars(parser.parse_args()) try: - client = messagebird.Client(args['accessKey']) + client = messagebird.Client(args['accessKey']) - msg = client.conversation_read_message(args['messageId']) + msg = client.conversation_read_message(args['messageId']) - # Print the object information. - print('\nThe following information was returned as a Conversation List object:\n') - print(' message id : %s' % msg.id) - print(' channel id : %s' % msg.channelId) - print(' direction : %s' % msg.direction) - print(' content : %s' % msg.content) - print(' content : %s' % msg.content) - print(' status : %s' % msg.status) - print(' type : %s' % msg.type) - print(' created date : %s' % msg.createdDatetime) - print(' updated date : %s' % msg.updatedDatetime) + # Print the object information. + print('\nThe following information was returned as a Conversation List object:\n') + print(' message id : %s' % msg.id) + print(' channel id : %s' % msg.channelId) + print(' direction : %s' % msg.direction) + print(' content : %s' % msg.content) + print(' content : %s' % msg.content) + print(' status : %s' % msg.status) + print(' type : %s' % msg.type) + print(' created date : %s' % msg.createdDatetime) + print(' updated date : %s' % msg.updatedDatetime) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Message object:\n') + print('\nAn error occured while requesting a Message object:\n') - for error in e.errors: - print(' code : %d' % error.code) - print(' description : %s' % error.description) - print(' parameter : %s\n' % error.parameter) + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/examples/conversation_read_webhook.py b/examples/conversation_read_webhook.py index 6a1b8e0..63c445e 100644 --- a/examples/conversation_read_webhook.py +++ b/examples/conversation_read_webhook.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import sys import messagebird import argparse @@ -9,22 +8,22 @@ args = vars(parser.parse_args()) try: - client = messagebird.Client(args['accessKey']) + client = messagebird.Client(args['accessKey']) - webhook = client.conversation_read_webhook(args['webhookId']) + webhook = client.conversation_read_webhook(args['webhookId']) - # Print the object information. - print('\nThe following information was returned as a Webhook object:\n') - print(' id : %s' % webhook.id) - print(' events : %s' % webhook.events) - print(' channel id : %s' % webhook.channelId) - print(' created date : %s' % webhook.createdDatetime) - print(' updated date : %s' % webhook.updatedDatetime) + # Print the object information. + print('\nThe following information was returned as a Webhook object:\n') + print(' id : %s' % webhook.id) + print(' events : %s' % webhook.events) + print(' channel id : %s' % webhook.channelId) + print(' created date : %s' % webhook.createdDatetime) + print(' updated date : %s' % webhook.updatedDatetime) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Webhook object:\n') + print('\nAn error occured while requesting a Webhook object:\n') - for error in e.errors: - print(' code : %d' % error.code) - print(' description : %s' % error.description) - print(' parameter : %s\n' % error.parameter) \ No newline at end of file + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/examples/conversation_start.py b/examples/conversation_start.py index 85e1968..a9a13bd 100644 --- a/examples/conversation_start.py +++ b/examples/conversation_start.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import sys import argparse import messagebird from messagebird.conversation_message import MESSAGE_TYPE_TEXT @@ -12,27 +11,29 @@ args = vars(parser.parse_args()) try: - client = messagebird.Client(args['accessKey']) + client = messagebird.Client(args['accessKey']) - msg = client.conversation_start({ 'channelId': args['channelId'], 'to': args['phoneNumber'], 'type': MESSAGE_TYPE_TEXT, 'content': { 'text': args['textMessage'] } }) + msg = client.conversation_start( + {'channelId': args['channelId'], 'to': args['phoneNumber'], 'type': MESSAGE_TYPE_TEXT, + 'content': {'text': args['textMessage']}}) - # Print the object information. - print('\nThe following information was returned as a Conversation object:\n') - print(' id : %s' % msg.id) - print(' contact id : %s' % msg.contactId) - print(' contact : %s' % msg.contact) - print(' last used channel id : %s' % msg.lastUsedChannelId) - print(' channels : %s' % msg.channels) - print(' messages : %s' % msg.messages) - print(' status : %s' % msg.status) - print(' createdDateTime : %s' % msg.createdDateTime) - print(' updatedDateTime : %s' % msg.updatedDateTime) - print(' lastReceivedDateTime : %s' % msg.lastReceivedDateTime) + # Print the object information. + print('\nThe following information was returned as a Conversation object:\n') + print(' id : %s' % msg.id) + print(' contact id : %s' % msg.contactId) + print(' contact : %s' % msg.contact) + print(' last used channel id : %s' % msg.lastUsedChannelId) + print(' channels : %s' % msg.channels) + print(' messages : %s' % msg.messages) + print(' status : %s' % msg.status) + print(' createdDateTime : %s' % msg.createdDateTime) + print(' updatedDateTime : %s' % msg.updatedDateTime) + print(' lastReceivedDateTime : %s' % msg.lastReceivedDateTime) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Message object:\n') + print('\nAn error occured while requesting a Message object:\n') - for error in e.errors: - print(' code : %d' % error.code) - print(' description : %s' % error.description) - print(' parameter : %s\n' % error.parameter) + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/examples/conversation_update.py b/examples/conversation_update.py index 7ad15e3..23fa2f4 100644 --- a/examples/conversation_update.py +++ b/examples/conversation_update.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import sys import argparse import messagebird @@ -9,24 +8,24 @@ args = vars(parser.parse_args()) try: - client = messagebird.Client(args['accessKey']) + client = messagebird.Client(args['accessKey']) - conversation = client.conversation_update(args['conversationId'], {'status': 'active'}) + conversation = client.conversation_update(args['conversationId'], {'status': 'active'}) - # Print the object information. - print('\nThe following information was returned as a Conversation object:\n') - print(' conversation id : %s' % conversation.id) - print(' contact id : %s' % conversation.contactId) - print(' messages total count : %s' % conversation.messages.totalCount) - print(' status : %s' % conversation.status) - print(' created date time : %s' % conversation.createdDatetime) - print(' updated date time : %s' % conversation.updatedDatetime) - print(' last received date time : %s' % conversation.lastReceivedDatetime) + # Print the object information. + print('\nThe following information was returned as a Conversation object:\n') + print(' conversation id : %s' % conversation.id) + print(' contact id : %s' % conversation.contactId) + print(' messages total count : %s' % conversation.messages.totalCount) + print(' status : %s' % conversation.status) + print(' created date time : %s' % conversation.createdDatetime) + print(' updated date time : %s' % conversation.updatedDatetime) + print(' last received date time : %s' % conversation.lastReceivedDatetime) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Conversation object:\n') + print('\nAn error occured while requesting a Conversation object:\n') - for error in e.errors: - print(' code : %d' % error.code) - print(' description : %s' % error.description) - print(' parameter : %s\n' % error.parameter) \ No newline at end of file + for error in e.errors: + print(' code : %d' % error.code) + print(' description : %s' % error.description) + print(' parameter : %s\n' % error.parameter) diff --git a/messagebird/client.py b/messagebird/client.py index 0360bd2..5b8b9c8 100644 --- a/messagebird/client.py +++ b/messagebird/client.py @@ -1,21 +1,21 @@ import sys import json -from messagebird.balance import Balance -from messagebird.contact import Contact, ContactList -from messagebird.error import Error -from messagebird.group import Group, GroupList -from messagebird.hlr import HLR -from messagebird.message import Message -from messagebird.voicemessage import VoiceMessage -from messagebird.lookup import Lookup -from messagebird.verify import Verify -from messagebird.http_client import HttpClient +from messagebird.balance import Balance +from messagebird.contact import Contact, ContactList +from messagebird.error import Error +from messagebird.group import Group, GroupList +from messagebird.hlr import HLR +from messagebird.message import Message +from messagebird.voicemessage import VoiceMessage +from messagebird.lookup import Lookup +from messagebird.verify import Verify +from messagebird.http_client import HttpClient from messagebird.conversation_message import ConversationMessage, ConversationMessageList -from messagebird.conversation import Conversation, ConversationList +from messagebird.conversation import Conversation, ConversationList from messagebird.conversation_webhook import ConversationWebhook, ConversationWebhookList -ENDPOINT = 'https://rest.messagebird.com' +ENDPOINT = 'https://rest.messagebird.com' CLIENT_VERSION = '1.3.1' PYTHON_VERSION = '%d.%d.%d' % (sys.version_info[0], sys.version_info[1], sys.version_info[2]) USER_AGENT = 'MessageBird/ApiClient/%s Python/%s' % (CLIENT_VERSION, PYTHON_VERSION) @@ -29,226 +29,227 @@ class ErrorException(Exception): - def __init__(self, errors): - self.errors = errors - message = ' '.join([str(e) for e in self.errors]) - super(ErrorException, self).__init__(message) + def __init__(self, errors): + self.errors = errors + message = ' '.join([str(e) for e in self.errors]) + super(ErrorException, self).__init__(message) class Client(object): - def __init__(self, access_key, http_client=None): - self.access_key = access_key - self.http_client = http_client + def __init__(self, access_key, http_client=None): + self.access_key = access_key + self.http_client = http_client - def _get_http_client(self, type=REST_TYPE): - if self.http_client: - return self.http_client + def _get_http_client(self, type=REST_TYPE): + if self.http_client: + return self.http_client - if type == REST_TYPE: - return HttpClient(ENDPOINT, self.access_key, USER_AGENT) + if type == REST_TYPE: + return HttpClient(ENDPOINT, self.access_key, USER_AGENT) - return HttpClient(CONVERSATION_API_ROOT, self.access_key, USER_AGENT) + return HttpClient(CONVERSATION_API_ROOT, self.access_key, USER_AGENT) - def request(self, path, method='GET', params=None, type=REST_TYPE): - """Builds a request, gets a response and decodes it.""" - response_text = self._get_http_client(type).request(path, method, params) + def request(self, path, method='GET', params=None, type=REST_TYPE): + """Builds a request, gets a response and decodes it.""" + response_text = self._get_http_client(type).request(path, method, params) - if not response_text: - return response_text - - response_json = json.loads(response_text) - - if 'errors' in response_json: - raise(ErrorException([Error().load(e) for e in response_json['errors']])) - - return response_json - - def request_plain_text(self, path, method='GET', params=None, type=REST_TYPE): - """Builds a request, gets a response and returns the body.""" - response_text = self._get_http_client(type).request(path, method, params) - - try: - # Try to decode the response to JSON to see if the API returned any - # errors. - response_json = json.loads(response_text) - - if 'errors' in response_json: - raise (ErrorException([Error().load(e) for e in response_json['errors']])) - except ValueError: - # Do nothing: json.loads throws if the input string is not valid JSON, - # which is expected. We'll just return the response body below. - pass + if not response_text: + return response_text - return response_text + response_json = json.loads(response_text) - def balance(self): - """Retrieve your balance.""" - return Balance().load(self.request('balance')) + if 'errors' in response_json: + raise (ErrorException([Error().load(e) for e in response_json['errors']])) - def hlr(self, id): - """Retrieve the information of a specific HLR lookup.""" - return HLR().load(self.request('hlr/' + str(id))) + return response_json - def hlr_create(self, msisdn, reference): - """Perform a new HLR lookup.""" - return HLR().load(self.request('hlr', 'POST', { 'msisdn' : msisdn, 'reference' : reference })) + def request_plain_text(self, path, method='GET', params=None, type=REST_TYPE): + """Builds a request, gets a response and returns the body.""" + response_text = self._get_http_client(type).request(path, method, params) - def message(self, id): - """Retrieve the information of a specific message.""" - return Message().load(self.request('messages/' + str(id))) + try: + # Try to decode the response to JSON to see if the API returned any + # errors. + response_json = json.loads(response_text) - def message_create(self, originator, recipients, body, params=None): - """Create a new message.""" - if params is None: params = {} - if type(recipients) == list: - recipients = ','.join(recipients) - - params.update({ 'originator' : originator, 'body' : body, 'recipients' : recipients }) - return Message().load(self.request('messages', 'POST', params)) + if 'errors' in response_json: + raise (ErrorException([Error().load(e) for e in response_json['errors']])) + except ValueError: + # Do nothing: json.loads throws if the input string is not valid JSON, + # which is expected. We'll just return the response body below. + pass - def message_delete(self, id): - """Delete a message from the dashboard.""" - self.request_plain_text('messages/' + str(id), 'DELETE') - - def voice_message(self, id): - "Retrieve the information of a specific voice message." - return VoiceMessage().load(self.request('voicemessages/' + str(id))) - - def voice_message_create(self, recipients, body, params=None): - """Create a new voice message.""" - if params is None: params = {} - if type(recipients) == list: - recipients = ','.join(recipients) - - params.update({ 'recipients' : recipients, 'body' : body }) - return VoiceMessage().load(self.request('voicemessages', 'POST', params)) - - def lookup(self, phonenumber, params=None): - """Do a new lookup.""" - if params is None: params = {} - return Lookup().load(self.request('lookup/' + str(phonenumber), 'GET', params)) - - def lookup_hlr(self, phonenumber, params=None): - """Retrieve the information of a specific HLR lookup.""" - if params is None: params = {} - return HLR().load(self.request('lookup/' + str(phonenumber) + '/hlr', 'GET', params)) - - def lookup_hlr_create(self, phonenumber, params=None): - """Perform a new HLR lookup.""" - if params is None: params = {} - return HLR().load(self.request('lookup/' + str(phonenumber) + '/hlr', 'POST', params)) + return response_text - def verify(self, id): - """Retrieve the information of a specific verification.""" - return Verify().load(self.request('verify/' + str(id))) + def balance(self): + """Retrieve your balance.""" + return Balance().load(self.request('balance')) + + def hlr(self, id): + """Retrieve the information of a specific HLR lookup.""" + return HLR().load(self.request('hlr/' + str(id))) + + def hlr_create(self, msisdn, reference): + """Perform a new HLR lookup.""" + return HLR().load(self.request('hlr', 'POST', {'msisdn': msisdn, 'reference': reference})) + + def message(self, id): + """Retrieve the information of a specific message.""" + return Message().load(self.request('messages/' + str(id))) + + def message_create(self, originator, recipients, body, params=None): + """Create a new message.""" + if params is None: params = {} + if type(recipients) == list: + recipients = ','.join(recipients) + + params.update({'originator': originator, 'body': body, 'recipients': recipients}) + return Message().load(self.request('messages', 'POST', params)) + + def message_delete(self, id): + """Delete a message from the dashboard.""" + self.request_plain_text('messages/' + str(id), 'DELETE') + + def voice_message(self, id): + "Retrieve the information of a specific voice message." + return VoiceMessage().load(self.request('voicemessages/' + str(id))) + + def voice_message_create(self, recipients, body, params=None): + """Create a new voice message.""" + if params is None: params = {} + if type(recipients) == list: + recipients = ','.join(recipients) + + params.update({'recipients': recipients, 'body': body}) + return VoiceMessage().load(self.request('voicemessages', 'POST', params)) + + def lookup(self, phonenumber, params=None): + """Do a new lookup.""" + if params is None: params = {} + return Lookup().load(self.request('lookup/' + str(phonenumber), 'GET', params)) + + def lookup_hlr(self, phonenumber, params=None): + """Retrieve the information of a specific HLR lookup.""" + if params is None: params = {} + return HLR().load(self.request('lookup/' + str(phonenumber) + '/hlr', 'GET', params)) + + def lookup_hlr_create(self, phonenumber, params=None): + """Perform a new HLR lookup.""" + if params is None: params = {} + return HLR().load(self.request('lookup/' + str(phonenumber) + '/hlr', 'POST', params)) - def verify_create(self, recipient, params=None): - """Create a new verification.""" - if params is None: params = {} - params.update({ 'recipient' : recipient }) - return Verify().load(self.request('verify', 'POST', params)) + def verify(self, id): + """Retrieve the information of a specific verification.""" + return Verify().load(self.request('verify/' + str(id))) - def verify_verify(self, id, token): - """Verify the token of a specific verification.""" - return Verify().load(self.request('verify/' + str(id), params={'token': token})) + def verify_create(self, recipient, params=None): + """Create a new verification.""" + if params is None: params = {} + params.update({'recipient': recipient}) + return Verify().load(self.request('verify', 'POST', params)) - def contact(self, id): - """Retrieve the information of a specific contact.""" - return Contact().load(self.request('contacts/' + str(id))) + def verify_verify(self, id, token): + """Verify the token of a specific verification.""" + return Verify().load(self.request('verify/' + str(id), params={'token': token})) - def contact_create(self, phonenumber, params=None): - if params is None: params = {} - params.update({'msisdn': phonenumber}) - return Contact().load(self.request('contacts', 'POST', params)) + def contact(self, id): + """Retrieve the information of a specific contact.""" + return Contact().load(self.request('contacts/' + str(id))) - def contact_delete(self, id): - self.request_plain_text('contacts/' + str(id), 'DELETE') - - def contact_update(self, id, params=None): - self.request_plain_text('contacts/' + str(id), 'PATCH', params) + def contact_create(self, phonenumber, params=None): + if params is None: params = {} + params.update({'msisdn': phonenumber}) + return Contact().load(self.request('contacts', 'POST', params)) - def contact_list(self, limit=10, offset=0): - query = self._format_query(limit, offset) - return ContactList().load(self.request('contacts?'+query, 'GET', None)) + def contact_delete(self, id): + self.request_plain_text('contacts/' + str(id), 'DELETE') - def group(self, id): - return Group().load(self.request('groups/' + str(id), 'GET', None)) + def contact_update(self, id, params=None): + self.request_plain_text('contacts/' + str(id), 'PATCH', params) - def group_create(self, name, params=None): - if params is None: params = {} - params.update({'name': name}) - return Group().load(self.request('groups', 'POST', params)) + def contact_list(self, limit=10, offset=0): + query = self._format_query(limit, offset) + return ContactList().load(self.request('contacts?' + query, 'GET', None)) - def group_delete(self, id): - self.request_plain_text('groups/' + str(id), 'DELETE', None) + def group(self, id): + return Group().load(self.request('groups/' + str(id), 'GET', None)) - def group_list(self, limit=10, offset=0): - query = self._format_query(limit, offset) - return GroupList().load(self.request('groups?'+query, 'GET', None)) + def group_create(self, name, params=None): + if params is None: params = {} + params.update({'name': name}) + return Group().load(self.request('groups', 'POST', params)) - def group_update(self, id, name, params=None): - if params is None: params = {} - params.update({'name': name}) - self.request_plain_text('groups/' + str(id), 'PATCH', params) + def group_delete(self, id): + self.request_plain_text('groups/' + str(id), 'DELETE', None) + + def group_list(self, limit=10, offset=0): + query = self._format_query(limit, offset) + return GroupList().load(self.request('groups?' + query, 'GET', None)) + + def group_update(self, id, name, params=None): + if params is None: params = {} + params.update({'name': name}) + self.request_plain_text('groups/' + str(id), 'PATCH', params) - def group_add_contacts(self, groupId, contactIds): - query = self.__group_add_contacts_query(contactIds) - self.request_plain_text('groups/' + str(groupId) + '?' + query, 'PUT', None) + def group_add_contacts(self, groupId, contactIds): + query = self.__group_add_contacts_query(contactIds) + self.request_plain_text('groups/' + str(groupId) + '?' + query, 'PUT', None) - def __group_add_contacts_query(self, contactIds): - # __group_add_contacts_query gets a query string to add contacts to a - # group. The expected format is ids[]=first-contact&ids[]=second-contact. - # See: https://developers.messagebird.com/docs/groups#add-contact-to-group. - return '&'.join('ids[]=' + str(id) for id in contactIds) + def __group_add_contacts_query(self, contactIds): + # __group_add_contacts_query gets a query string to add contacts to a + # group. The expected format is ids[]=first-contact&ids[]=second-contact. + # See: https://developers.messagebird.com/docs/groups#add-contact-to-group. + return '&'.join('ids[]=' + str(id) for id in contactIds) - def group_remove_contact(self, groupId, contactId): - self.request_plain_text('groups/' + str(groupId) + '/contacts/' + str(contactId), 'DELETE', None) + def group_remove_contact(self, groupId, contactId): + self.request_plain_text('groups/' + str(groupId) + '/contacts/' + str(contactId), 'DELETE', None) - def conversation_list(self, limit=10, offset=0): - uri = CONVERSATION_PATH + '?' + self._format_query(limit, offset) - return ConversationList().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) + def conversation_list(self, limit=10, offset=0): + uri = CONVERSATION_PATH + '?' + self._format_query(limit, offset) + return ConversationList().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) - def conversation_start(self, start_request): - uri = CONVERSATION_PATH + '/start' - return Conversation().load(self.request(uri, 'POST', start_request, CONVERSATION_TYPE)) + def conversation_start(self, start_request): + uri = CONVERSATION_PATH + '/start' + return Conversation().load(self.request(uri, 'POST', start_request, CONVERSATION_TYPE)) - def conversation_update(self, id, update_request): - uri = CONVERSATION_PATH + '/' + str(id) - return Conversation().load(self.request(uri, 'PATCH', update_request, CONVERSATION_TYPE)) + def conversation_update(self, id, update_request): + uri = CONVERSATION_PATH + '/' + str(id) + return Conversation().load(self.request(uri, 'PATCH', update_request, CONVERSATION_TYPE)) - def conversation_read(self, id): - uri = CONVERSATION_PATH + '/' + str(id) - return Conversation().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) + def conversation_read(self, id): + uri = CONVERSATION_PATH + '/' + str(id) + return Conversation().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) - def conversation_list_messages(self, conversation_id, limit=10, offset=0): - uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH - uri += '?' + self._format_query(limit, offset) + def conversation_list_messages(self, conversation_id, limit=10, offset=0): + uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH + uri += '?' + self._format_query(limit, offset) - return ConversationMessageList().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) + return ConversationMessageList().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) - def conversation_create_message(self, conversation_id, message_create_request): - uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH - return ConversationMessage().load(self.request(uri, 'POST', message_create_request, CONVERSATION_TYPE)) + def conversation_create_message(self, conversation_id, message_create_request): + uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH + return ConversationMessage().load(self.request(uri, 'POST', message_create_request, CONVERSATION_TYPE)) - def conversation_read_message(self, message_id): - uri = CONVERSATION_MESSAGES_PATH + '/' + str(message_id) - return ConversationMessage().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) + def conversation_read_message(self, message_id): + uri = CONVERSATION_MESSAGES_PATH + '/' + str(message_id) + return ConversationMessage().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) - def conversation_create_webhook(self, webhook_create_request): - return ConversationWebhook().load(self.request(CONVERSATION_WEB_HOOKS_PATH, 'POST', webhook_create_request, CONVERSATION_TYPE)) + def conversation_create_webhook(self, webhook_create_request): + return ConversationWebhook().load( + self.request(CONVERSATION_WEB_HOOKS_PATH, 'POST', webhook_create_request, CONVERSATION_TYPE)) - def conversation_delete_webhook(self, id): - uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id) - self.request(uri, 'DELETE', None, CONVERSATION_TYPE) + def conversation_delete_webhook(self, id): + uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id) + self.request(uri, 'DELETE', None, CONVERSATION_TYPE) - def conversation_list_webhooks(self, limit=10, offset=0): - uri = CONVERSATION_WEB_HOOKS_PATH + '?' + self._format_query(limit, offset) + def conversation_list_webhooks(self, limit=10, offset=0): + uri = CONVERSATION_WEB_HOOKS_PATH + '?' + self._format_query(limit, offset) - return ConversationWebhookList().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) + return ConversationWebhookList().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) - def conversation_read_webhook(self, id): - uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id) - return ConversationWebhook().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) + def conversation_read_webhook(self, id): + uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id) + return ConversationWebhook().load(self.request(uri, 'GET', None, CONVERSATION_TYPE)) - def _format_query(self, limit, offset): - return 'limit='+str(limit)+'&offset='+str(offset) + def _format_query(self, limit, offset): + return 'limit=' + str(limit) + '&offset=' + str(offset) diff --git a/messagebird/conversation_channel.py b/messagebird/conversation_channel.py index 7f359ca..58fe0c8 100644 --- a/messagebird/conversation_channel.py +++ b/messagebird/conversation_channel.py @@ -1,5 +1,6 @@ from messagebird.base import Base + class Channel(Base): def __init__(self): self.id = None @@ -23,4 +24,4 @@ def updatedDateTime(self): @updatedDateTime.setter def updatedDateTime(self, value): - self._updatedDateTime = self.value_to_time(value) \ No newline at end of file + self._updatedDateTime = self.value_to_time(value) diff --git a/messagebird/conversation_contact.py b/messagebird/conversation_contact.py index 4c58a62..5addd4b 100644 --- a/messagebird/conversation_contact.py +++ b/messagebird/conversation_contact.py @@ -36,4 +36,4 @@ def updatedDatetime(self): @updatedDatetime.setter def updatedDatetime(self, value): - self._updatedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') \ No newline at end of file + self._updatedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') diff --git a/tests/test_conversation.py b/tests/test_conversation.py index 8ea30bd..dc27e64 100644 --- a/tests/test_conversation.py +++ b/tests/test_conversation.py @@ -17,7 +17,7 @@ def test_conversation_start(self): http_client.request.return_value = '{"id":"1234","contactId":"1234","contact":{"id":"1234","href":"https://contacts.messagebird.com/v2/contacts/1234","msisdn":99999999999,"displayName":"99999999999","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:19:38Z"},"channels":[{"id":"1234","name":"channel-name","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:54:42.497114599Z","lastReceivedDatetime":"2019-04-02T08:54:42.464955904Z","lastUsedChannelId":"1234","messages":{"totalCount":1,"href":"https://conversations.messagebird.com/v1/conversations/1234/messages"}}' data = { - 'channelId': '1234', + 'channelId': '1234', 'to': '+99999999999', 'type': "text", 'content': { @@ -63,9 +63,9 @@ def test_conversation_update(self): http_client = Mock() http_client.request.return_value = '{"id":"07e823fdb36a462fb5e187d6d7b96493","contactId":"459a35432b0c4195abbdae353eb19359","status":"archived","createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-03T07:22:58.965421128Z","lastReceivedDatetime":"2019-04-02T12:02:22.707634424Z","lastUsedChannelId":"c0dae31e440145e094c4708b7d908842","messages":{"totalCount":16,"href":"https://conversations.messagebird.com/v1/conversations/07e823fdb36a462fb5e187d6d7b96493/messages"}}' - updatedRequestData = {'status': 'archived'} + updated_request_data = {'status': 'archived'} - conversation = Client('', http_client).conversation_update('conversation-id', updatedRequestData) + conversation = Client('', http_client).conversation_update('conversation-id', updated_request_data) - http_client.request.assert_called_once_with('conversations/conversation-id', 'PATCH', updatedRequestData) - self.assertEqual('archived', conversation.status) \ No newline at end of file + http_client.request.assert_called_once_with('conversations/conversation-id', 'PATCH', updated_request_data) + self.assertEqual('archived', conversation.status) diff --git a/tests/test_conversation_message.py b/tests/test_conversation_message.py index 47e9f3c..4c6836b 100644 --- a/tests/test_conversation_message.py +++ b/tests/test_conversation_message.py @@ -36,7 +36,7 @@ def test_create_message(self): http_client.request.return_value = '{"id":"id","conversationId":"conversation-id","channelId":"channel-id","type":"text","content":{"text":"Example Text Message"},"direction":"sent","status":"pending","createdDatetime":"2019-04-02T11:57:52.142641447Z","updatedDatetime":"2019-04-02T11:57:53.142641447Z"}' data = { - 'channelId': 1234, + 'channelId': 1234, 'type': 'text', 'content': { 'text': 'this is a message' @@ -48,4 +48,4 @@ def test_create_message(self): self.assertEqual(datetime(2019, 4, 2, 11, 57, 53), msg.updatedDatetime) self.assertEqual(datetime(2019, 4, 2, 11, 57, 52), msg.createdDatetime) - http_client.request.assert_called_once_with('conversations/conversation-id/messages', 'POST', data) \ No newline at end of file + http_client.request.assert_called_once_with('conversations/conversation-id/messages', 'POST', data) diff --git a/tests/test_conversation_webhook.py b/tests/test_conversation_webhook.py index 85a6fd9..ec009e8 100644 --- a/tests/test_conversation_webhook.py +++ b/tests/test_conversation_webhook.py @@ -2,7 +2,7 @@ from datetime import datetime from messagebird import Client from messagebird.conversation_webhook import \ - CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED,\ + CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED, \ CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED try: @@ -20,9 +20,10 @@ def test_conversation_webhook_create(self): http_client.request.return_value = '{"id":"20c308852190485bbb658e43baffc5fa","url":"https://example.com","channelId":"c0dae31e440145e094c4708b7d908842","events":["conversation.created","conversation.updated"],"status":"enabled","createdDatetime":"2019-04-03T07:46:37.984026573Z","updatedDatetime":null}' webhookRequestData = { - 'channelId': '20c308852190485bbb658e43baffc5fa', - 'events': [CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED, CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED], - 'url': 'https://example.com' + 'channelId': '20c308852190485bbb658e43baffc5fa', + 'events': [CONVERSATION_WEBHOOK_EVENT_CONVERSATION_CREATED, + CONVERSATION_WEBHOOK_EVENT_CONVERSATION_UPDATED], + 'url': 'https://example.com' } Client('', http_client).conversation_create_webhook(webhookRequestData) @@ -55,9 +56,9 @@ def test_conversation_webhook_read(self): http_client = Mock() http_client.request.return_value = '{"id":"5031e2da142d401c93fbc38518ebb604","url":"https://example.com","channelId":"c0dae31e440145e094c4708b7d908842","events":["conversation.created","conversation.updated"],"status":"enabled","createdDatetime":"2019-04-03T08:41:37Z","updatedDatetime":null}' - webhook = Client('', http_client).conversation_read_webhook('webhook-id') + web_hook = Client('', http_client).conversation_read_webhook('webhook-id') http_client.request.assert_called_once_with('webhooks/webhook-id', 'GET', None) - self.assertEqual(datetime(2019, 4, 3, 8, 41, 37), webhook.createdDatetime) - self.assertEqual(None, webhook.updatedDatetime) - self.assertEqual(['conversation.created', 'conversation.updated'], webhook.events) \ No newline at end of file + self.assertEqual(datetime(2019, 4, 3, 8, 41, 37), web_hook.createdDatetime) + self.assertEqual(None, web_hook.updatedDatetime) + self.assertEqual(['conversation.created', 'conversation.updated'], web_hook.events) From f532fca3daefc49176bedcfe41f2a458806bbf5a Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Tue, 9 Apr 2019 11:31:40 +0200 Subject: [PATCH 15/16] Use str to represent object as string --- examples/conversation_create_message.py | 12 ++--------- examples/conversation_create_webhook.py | 8 ++------ examples/conversation_delete_webhook.py | 2 +- examples/conversation_list.py | 13 +++--------- examples/conversation_list_messages.py | 11 ++-------- examples/conversation_list_webhook.py | 13 +++--------- examples/conversation_read.py | 10 ++------- examples/conversation_read_message.py | 12 ++--------- examples/conversation_read_webhook.py | 8 ++------ examples/conversation_start.py | 13 ++---------- examples/conversation_update.py | 10 ++------- messagebird/conversation.py | 27 ++++++++++++++++++++++++- messagebird/conversation_message.py | 25 +++++++++++++++++++++++ messagebird/conversation_webhook.py | 22 ++++++++++++++++++++ 14 files changed, 96 insertions(+), 90 deletions(-) diff --git a/examples/conversation_create_message.py b/examples/conversation_create_message.py index 5e50ef0..1daee46 100644 --- a/examples/conversation_create_message.py +++ b/examples/conversation_create_message.py @@ -19,16 +19,8 @@ 'content': {'text': args['message']}}) # Print the object information. - print('\nThe following information was returned as a Conversation List object:\n') - print(' message id : %s' % msg.id) - print(' channel id : %s' % msg.channelId) - print(' direction : %s' % msg.direction) - print(' content : %s' % msg.content) - print(' content : %s' % msg.content) - print(' status : %s' % msg.status) - print(' type : %s' % msg.type) - print(' created date : %s' % msg.createdDatetime) - print(' updated date : %s' % msg.updatedDatetime) + print('The following information was returned as a Conversation List object:\n') + print(msg) except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a Message object:\n') diff --git a/examples/conversation_create_webhook.py b/examples/conversation_create_webhook.py index 5b171ba..eb0d6d0 100644 --- a/examples/conversation_create_webhook.py +++ b/examples/conversation_create_webhook.py @@ -21,12 +21,8 @@ }) # Print the object information. - print('\nThe following information was returned as a Webhook object:\n') - print(' id : %s' % webhook.id) - print(' events : %s' % webhook.events) - print(' channel id : %s' % webhook.channelId) - print(' created date : %s' % webhook.createdDatetime) - print(' updated date : %s' % webhook.updatedDatetime) + print('The following information was returned as a Webhook object:') + print(webhook) except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a Webhook object:\n') diff --git a/examples/conversation_delete_webhook.py b/examples/conversation_delete_webhook.py index 4f65211..93cfce4 100644 --- a/examples/conversation_delete_webhook.py +++ b/examples/conversation_delete_webhook.py @@ -13,7 +13,7 @@ client.conversation_delete_webhook(args['webhookId']) # Print the object information. - print('\nWebhook has been deleted:\n') + print('Webhook has been deleted') except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a Webhook object:\n') diff --git a/examples/conversation_list.py b/examples/conversation_list.py index 236c596..991d0d2 100644 --- a/examples/conversation_list.py +++ b/examples/conversation_list.py @@ -11,19 +11,12 @@ conversationList = client.conversation_list() - itemIds = [] - for msgItem in conversationList.items: - itemIds.append(msgItem.id) - # Print the object information. - print('\nThe following information was returned as a Conversation List object:\n') - print(' conversation ids : %s' % itemIds) - print(' offset : %s' % conversationList.offset) - print(' limit : %s' % conversationList.limit) - print(' totalCount : %s' % conversationList.totalCount) + print('The following information was returned as a Conversation List object:') + print(conversationList) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Message object:\n') + print('An error occured while requesting a Message object:') for error in e.errors: print(' code : %d' % error.code) diff --git a/examples/conversation_list_messages.py b/examples/conversation_list_messages.py index 7fb3d12..0c1e6a6 100644 --- a/examples/conversation_list_messages.py +++ b/examples/conversation_list_messages.py @@ -12,16 +12,9 @@ msg = client.conversation_list_messages(args['conversationId']) - itemIds = [] - for msgItem in msg.items: - itemIds.append(msgItem.id) - # Print the object information. - print('\nThe following information was returned as a Conversation Message List object:\n') - print(' message ids : %s' % itemIds) - print(' offset : %s' % msg.offset) - print(' limit : %s' % msg.limit) - print(' totalCount : %s' % msg.totalCount) + print('The following information was returned as a Conversation Message List object:') + print(msg) except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a Conversation Message List object:\n') diff --git a/examples/conversation_list_webhook.py b/examples/conversation_list_webhook.py index d0cdd28..962d82a 100644 --- a/examples/conversation_list_webhook.py +++ b/examples/conversation_list_webhook.py @@ -9,18 +9,11 @@ try: client = messagebird.Client(args['accessKey']) - webhookList = client.conversation_list_webhooks() - - itemIds = [] - for msgItem in webhookList.items: - itemIds.append(msgItem.id) + webhook_list = client.conversation_list_webhooks() # Print the object information. - print('\nThe following information was returned as a Conversation Webhook List object:\n') - print(' conversation ids : %s' % itemIds) - print(' offset : %s' % webhookList.offset) - print(' limit : %s' % webhookList.limit) - print(' totalCount : %s' % webhookList.totalCount) + print('The following information was returned as a Conversation Webhook List object:') + print(webhook_list) except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a Conversation Webhook List object:\n') diff --git a/examples/conversation_read.py b/examples/conversation_read.py index d817ff1..42ec21d 100644 --- a/examples/conversation_read.py +++ b/examples/conversation_read.py @@ -13,14 +13,8 @@ conversation = client.conversation_read(args['conversationId']) # Print the object information. - print('\nThe following information was returned as a Conversation object:\n') - print(' conversation id : %s' % conversation.id) - print(' contact id : %s' % conversation.contactId) - print(' messages total count : %s' % conversation.messages.totalCount) - print(' status : %s' % conversation.status) - print(' created date time : %s' % conversation.createdDatetime) - print(' updated date time : %s' % conversation.updatedDatetime) - print(' last received date time : %s' % conversation.lastReceivedDatetime) + print('The following information was returned as a Conversation object:') + print(conversation) except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a Conversation object:\n') diff --git a/examples/conversation_read_message.py b/examples/conversation_read_message.py index 3f9371b..c9d84f6 100644 --- a/examples/conversation_read_message.py +++ b/examples/conversation_read_message.py @@ -13,16 +13,8 @@ msg = client.conversation_read_message(args['messageId']) # Print the object information. - print('\nThe following information was returned as a Conversation List object:\n') - print(' message id : %s' % msg.id) - print(' channel id : %s' % msg.channelId) - print(' direction : %s' % msg.direction) - print(' content : %s' % msg.content) - print(' content : %s' % msg.content) - print(' status : %s' % msg.status) - print(' type : %s' % msg.type) - print(' created date : %s' % msg.createdDatetime) - print(' updated date : %s' % msg.updatedDatetime) + print('The following information was returned as a Conversation List object:') + print(msg) except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a Message object:\n') diff --git a/examples/conversation_read_webhook.py b/examples/conversation_read_webhook.py index 63c445e..d8efe4b 100644 --- a/examples/conversation_read_webhook.py +++ b/examples/conversation_read_webhook.py @@ -13,12 +13,8 @@ webhook = client.conversation_read_webhook(args['webhookId']) # Print the object information. - print('\nThe following information was returned as a Webhook object:\n') - print(' id : %s' % webhook.id) - print(' events : %s' % webhook.events) - print(' channel id : %s' % webhook.channelId) - print(' created date : %s' % webhook.createdDatetime) - print(' updated date : %s' % webhook.updatedDatetime) + print('The following information was returned as a Webhook object:') + print(webhook) except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a Webhook object:\n') diff --git a/examples/conversation_start.py b/examples/conversation_start.py index a9a13bd..d4103d1 100644 --- a/examples/conversation_start.py +++ b/examples/conversation_start.py @@ -18,17 +18,8 @@ 'content': {'text': args['textMessage']}}) # Print the object information. - print('\nThe following information was returned as a Conversation object:\n') - print(' id : %s' % msg.id) - print(' contact id : %s' % msg.contactId) - print(' contact : %s' % msg.contact) - print(' last used channel id : %s' % msg.lastUsedChannelId) - print(' channels : %s' % msg.channels) - print(' messages : %s' % msg.messages) - print(' status : %s' % msg.status) - print(' createdDateTime : %s' % msg.createdDateTime) - print(' updatedDateTime : %s' % msg.updatedDateTime) - print(' lastReceivedDateTime : %s' % msg.lastReceivedDateTime) + print('The following information was returned as a Conversation object:') + print(msg) except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a Message object:\n') diff --git a/examples/conversation_update.py b/examples/conversation_update.py index 23fa2f4..94d4d96 100644 --- a/examples/conversation_update.py +++ b/examples/conversation_update.py @@ -13,14 +13,8 @@ conversation = client.conversation_update(args['conversationId'], {'status': 'active'}) # Print the object information. - print('\nThe following information was returned as a Conversation object:\n') - print(' conversation id : %s' % conversation.id) - print(' contact id : %s' % conversation.contactId) - print(' messages total count : %s' % conversation.messages.totalCount) - print(' status : %s' % conversation.status) - print(' created date time : %s' % conversation.createdDatetime) - print(' updated date time : %s' % conversation.updatedDatetime) - print(' last received date time : %s' % conversation.lastReceivedDatetime) + print('The following information was returned as a Conversation object:') + print(conversation) except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a Conversation object:\n') diff --git a/messagebird/conversation.py b/messagebird/conversation.py index 591fa96..d62dce6 100644 --- a/messagebird/conversation.py +++ b/messagebird/conversation.py @@ -74,6 +74,18 @@ def lastReceivedDatetime(self): def lastReceivedDatetime(self, value): self._lastReceivedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') + def __str__(self): + return "\n".join([ + 'id : %s' % self.id, + 'contact id : %s' % self.contactId, + 'last used channel id : %s' % self.lastUsedChannelId, + 'message total count : %s' % self.messages.totalCount, + 'status : %s' % self.status, + 'created date time : %s' % self.createdDatetime, + 'updated date time : %s' % self.updatedDatetime, + 'last received date : %s' % self.lastReceivedDatetime, + ]) + class ConversationList(Base): def __init__(self): @@ -92,4 +104,17 @@ def items(self, value): if isinstance(value, list): self._items = [] for item in value: - self._items.append(Conversation().load(item)) \ No newline at end of file + self._items.append(Conversation().load(item)) + + def __str__(self): + item_ids = [] + for msg_item in self._items: + item_ids.append(msg_item.id) + + return "\n".join([ + 'items IDs : %s' % item_ids, + 'offset : %s' % self.offset, + 'limit : %s' % self.limit, + 'count : %s' % self.count, + 'totalCount : %s' % self.totalCount, + ]) diff --git a/messagebird/conversation_message.py b/messagebird/conversation_message.py index 752d4b6..f9d1032 100644 --- a/messagebird/conversation_message.py +++ b/messagebird/conversation_message.py @@ -40,6 +40,18 @@ def updatedDatetime(self, value): if value is not None: self._updatedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') + def __str__(self): + return "\n".join([ + 'message id : %s' % self.id, + 'channel id : %s' % self.channelId, + 'direction : %s' % self.direction, + 'status : %s' % self.status, + 'type : %s' % self.type, + 'content : %s' % self.content, + 'created date time : %s' % self._createdDatetime, + 'updated date time : %s' % self._updatedDatetime + ]) + class ConversationMessageReference(Base): def __init__(self): @@ -68,3 +80,16 @@ def items(self, value): items.append(ConversationMessage().load(item)) self._items = items + + def __str__(self): + item_ids = [] + for msg_item in self._items: + item_ids.append(msg_item.id) + + return "\n".join([ + 'items IDs : %s' % item_ids, + 'offset : %s' % self.offset, + 'limit : %s' % self.limit, + 'count : %s' % self.count, + 'totalCount : %s' % self.totalCount, + ]) diff --git a/messagebird/conversation_webhook.py b/messagebird/conversation_webhook.py index 727d51c..9729743 100644 --- a/messagebird/conversation_webhook.py +++ b/messagebird/conversation_webhook.py @@ -32,6 +32,15 @@ def updatedDatetime(self): def updatedDatetime(self, value): self._updatedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ') + def __str__(self): + return "\n".join([ + 'id : %s' % self.id, + 'events : %s' % self.events, + 'channel id : %s' % self.channelId, + 'created date time : %s' % self.createdDatetime, + 'updated date time : %s' % self.updatedDatetime + ]) + class ConversationWebhookList(Base): def __init__(self): @@ -53,3 +62,16 @@ def items(self, value): items.append(ConversationWebhook().load(item)) self._items = items + + def __str__(self): + item_ids = [] + for item in self._items: + item_ids.append(item.id) + + return "\n".join([ + 'items IDs : %s' % item_ids, + 'offset : %s' % self.offset, + 'limit : %s' % self.limit, + 'count : %s' % self.count, + 'totalCount : %s' % self.totalCount, + ]) From b948d791a8f9b11dd16ef8b69e3dc78a576df1c0 Mon Sep 17 00:00:00 2001 From: Guilherme Lopes Date: Thu, 11 Apr 2019 09:11:54 +0200 Subject: [PATCH 16/16] Remove \n from examples --- examples/conversation_create_message.py | 4 ++-- examples/conversation_create_webhook.py | 2 +- examples/conversation_delete_webhook.py | 2 +- examples/conversation_list_messages.py | 2 +- examples/conversation_list_webhook.py | 2 +- examples/conversation_read.py | 2 +- examples/conversation_read_message.py | 2 +- examples/conversation_read_webhook.py | 2 +- examples/conversation_start.py | 2 +- examples/conversation_update.py | 2 +- 10 files changed, 11 insertions(+), 11 deletions(-) diff --git a/examples/conversation_create_message.py b/examples/conversation_create_message.py index 1daee46..38b0dc3 100644 --- a/examples/conversation_create_message.py +++ b/examples/conversation_create_message.py @@ -19,11 +19,11 @@ 'content': {'text': args['message']}}) # Print the object information. - print('The following information was returned as a Conversation List object:\n') + print('The following information was returned as a Conversation List object:') print(msg) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Message object:\n') + print('An error occured while requesting a Message object:') for error in e.errors: print(' code : %d' % error.code) diff --git a/examples/conversation_create_webhook.py b/examples/conversation_create_webhook.py index eb0d6d0..abc459b 100644 --- a/examples/conversation_create_webhook.py +++ b/examples/conversation_create_webhook.py @@ -25,7 +25,7 @@ print(webhook) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Webhook object:\n') + print('An error occured while requesting a Webhook object:') for error in e.errors: print(' code : %d' % error.code) diff --git a/examples/conversation_delete_webhook.py b/examples/conversation_delete_webhook.py index 93cfce4..4f4a21d 100644 --- a/examples/conversation_delete_webhook.py +++ b/examples/conversation_delete_webhook.py @@ -16,7 +16,7 @@ print('Webhook has been deleted') except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Webhook object:\n') + print('An error occured while requesting a Webhook object:') for error in e.errors: print(' code : %d' % error.code) diff --git a/examples/conversation_list_messages.py b/examples/conversation_list_messages.py index 0c1e6a6..7c58d3a 100644 --- a/examples/conversation_list_messages.py +++ b/examples/conversation_list_messages.py @@ -17,7 +17,7 @@ print(msg) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Conversation Message List object:\n') + print('An error occured while requesting a Conversation Message List object:') for error in e.errors: print(' code : %d' % error.code) diff --git a/examples/conversation_list_webhook.py b/examples/conversation_list_webhook.py index 962d82a..12a2e72 100644 --- a/examples/conversation_list_webhook.py +++ b/examples/conversation_list_webhook.py @@ -16,7 +16,7 @@ print(webhook_list) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Conversation Webhook List object:\n') + print('An error occured while requesting a Conversation Webhook List object:') for error in e.errors: print(' code : %d' % error.code) diff --git a/examples/conversation_read.py b/examples/conversation_read.py index 42ec21d..71260d6 100644 --- a/examples/conversation_read.py +++ b/examples/conversation_read.py @@ -17,7 +17,7 @@ print(conversation) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Conversation object:\n') + print('An error occured while requesting a Conversation object:') for error in e.errors: print(' code : %d' % error.code) diff --git a/examples/conversation_read_message.py b/examples/conversation_read_message.py index c9d84f6..afe1841 100644 --- a/examples/conversation_read_message.py +++ b/examples/conversation_read_message.py @@ -17,7 +17,7 @@ print(msg) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Message object:\n') + print('An error occured while requesting a Message object:') for error in e.errors: print(' code : %d' % error.code) diff --git a/examples/conversation_read_webhook.py b/examples/conversation_read_webhook.py index d8efe4b..3282787 100644 --- a/examples/conversation_read_webhook.py +++ b/examples/conversation_read_webhook.py @@ -17,7 +17,7 @@ print(webhook) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Webhook object:\n') + print('An error occured while requesting a Webhook object:') for error in e.errors: print(' code : %d' % error.code) diff --git a/examples/conversation_start.py b/examples/conversation_start.py index d4103d1..b4973da 100644 --- a/examples/conversation_start.py +++ b/examples/conversation_start.py @@ -22,7 +22,7 @@ print(msg) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Message object:\n') + print('An error occured while requesting a Message object:') for error in e.errors: print(' code : %d' % error.code) diff --git a/examples/conversation_update.py b/examples/conversation_update.py index 94d4d96..ffbca12 100644 --- a/examples/conversation_update.py +++ b/examples/conversation_update.py @@ -17,7 +17,7 @@ print(conversation) except messagebird.client.ErrorException as e: - print('\nAn error occured while requesting a Conversation object:\n') + print('An error occured while requesting a Conversation object:') for error in e.errors: print(' code : %d' % error.code)