Esempio n. 1
0
def test_post_to_public_account_sanity():
    sender = "012345A="
    text = "hi!"
    message_token = "a token"

    def post_request(endpoint, payload):
        data = json.loads(payload)
        assert endpoint == BOT_API_ENDPOINT.POST
        assert data['auth_token'] == VIBER_BOT_CONFIGURATION.auth_token
        assert data['from'] == sender
        assert data['sender']['name'] == VIBER_BOT_CONFIGURATION.name
        assert data['sender']['avatar'] == VIBER_BOT_CONFIGURATION.avatar
        assert data['text'] == text
        return dict(status=0, message_token=message_token)

    request_sender = Stub()
    request_sender.post_request = post_request

    text_message = TextMessage(text=text)

    message_sender = MessageSender(LOGGER, request_sender,
                                   VIBER_BOT_CONFIGURATION)
    token = message_sender.post_to_public_account(
        sender, VIBER_BOT_CONFIGURATION.name, VIBER_BOT_CONFIGURATION.avatar,
        text_message)
    assert token == message_token
Esempio n. 2
0
def test_send_message_sanity():
    to = "012345A="
    text = "hi!"
    message_token = "a token"
    chat_id = 'my chat id sample'

    def post_request(endpoint, payload):
        data = json.loads(payload)
        assert endpoint == BOT_API_ENDPOINT.SEND_MESSAGE
        assert data['auth_token'] == VIBER_BOT_CONFIGURATION.auth_token
        assert data['receiver'] == to
        assert data['sender']['name'] == VIBER_BOT_CONFIGURATION.name
        assert data['sender']['avatar'] == VIBER_BOT_CONFIGURATION.avatar
        assert data['text'] == text
        assert data['chat_id'] == chat_id
        return dict(status=0, message_token=message_token)

    request_sender = Stub()
    request_sender.post_request = post_request

    text_message = TextMessage(text=text)

    message_sender = MessageSender(LOGGER, request_sender,
                                   VIBER_BOT_CONFIGURATION)
    token = message_sender.send_message(to, VIBER_BOT_CONFIGURATION.name,
                                        VIBER_BOT_CONFIGURATION.avatar,
                                        text_message, chat_id)
    assert token == message_token
Esempio n. 3
0
 def __init__(self, bot_configuration):
     self._logger = logging.getLogger('viber.bot.api')
     self._bot_configuration = bot_configuration
     self._request_sender = ApiRequestSender(self._logger,
                                             VIBER_BOT_API_URL,
                                             bot_configuration,
                                             VIBER_BOT_USER_AGENT)
     self._message_sender = MessageSender(self._logger,
                                          self._request_sender,
                                          bot_configuration)
Esempio n. 4
0
def test_message_invalid():
    to = "012345A="

    def post_request(endpoint, payload):
        pytest.fail("message sender not supposed to call post_request")

    request_sender = Stub()
    request_sender.post_request = post_request

    text_message = TextMessage(text=None)

    message_sender = MessageSender(LOGGER, request_sender,
                                   VIBER_BOT_CONFIGURATION)
    with pytest.raises(Exception) as exc:
        message_sender.send_message(to, VIBER_BOT_CONFIGURATION.name,
                                    VIBER_BOT_CONFIGURATION.avatar,
                                    text_message)

        assert exc.value.message.startswith("failed validating message:")
Esempio n. 5
0
def test_send_result_failed():
    to = "012345A="
    text = "hi!"

    def post_request(endpoint, payload):
        data = json.loads(payload)
        return dict(status=1, status_message="failed")

    request_sender = Stub()
    request_sender.post_request = post_request

    text_message = TextMessage(text=text)

    message_sender = MessageSender(LOGGER, request_sender,
                                   VIBER_BOT_CONFIGURATION)
    with pytest.raises(Exception) as exc:
        message_sender.send_message(to, VIBER_BOT_CONFIGURATION.name,
                                    VIBER_BOT_CONFIGURATION.avatar,
                                    text_message)

        assert exc.value.message.startswith(
            "failed with status: 1, message: failed")
Esempio n. 6
0
class Api(object):
    def __init__(self, bot_configuration):
        self._logger = logging.getLogger('viber.bot.api')
        self._bot_configuration = bot_configuration
        self._request_sender = ApiRequestSender(self._logger,
                                                VIBER_BOT_API_URL,
                                                bot_configuration,
                                                VIBER_BOT_USER_AGENT)
        self._message_sender = MessageSender(self._logger,
                                             self._request_sender,
                                             bot_configuration)

    @property
    def name(self):
        return self._bot_configuration.name

    @property
    def avatar(self):
        return self._bot_configuration.avatar

    def set_webhook(self, url, webhook_events=None, is_inline=False):
        self._logger.debug(u"setting webhook to url: {0}".format(url))
        return self._request_sender.set_webhook(url, webhook_events, is_inline)

    def unset_webhook(self):
        self._logger.debug("unsetting webhook")
        return self._request_sender.set_webhook('')

    def get_online(self, ids):
        return self._request_sender.get_online_status(ids)

    def get_user_details(self, user_id):
        return self._request_sender.get_user_details(user_id)

    def get_account_info(self):
        self._logger.debug("requesting account info")
        account_info = self._request_sender.get_account_info()
        self._logger.debug(u"received account info: {0}".format(account_info))
        return account_info

    def verify_signature(self, request_data, signature):
        return signature == self._calculate_message_signature(request_data)

    def parse_request(self, request_data):
        self._logger.debug("parsing request")
        request_dict = json.loads(request_data.decode(
        ) if isinstance(request_data, bytes) else request_data)
        request = create_request(request_dict)
        self._logger.debug(u"parsed request={0}".format(request))
        return request

    def send_messages(self, to, messages, chat_id=None):
        """
		:param to: Viber user id
		:param messages: list of Message objects to be sent
		:param chat_id: Optional. String. Indicates that this is a message sent in inline conversation.
		:return: list of tokens of the sent messages
		"""
        self._logger.debug("going to send messages: {0}, to: {1}".format(
            messages, to))
        if not isinstance(messages, list):
            messages = [messages]

        sent_messages_tokens = []

        for message in messages:
            token = self._message_sender.send_message(
                to, self._bot_configuration.name,
                self._bot_configuration.avatar, message, chat_id)
            sent_messages_tokens.append(token)

        return sent_messages_tokens

    def post_messages_to_public_account(self, sender, messages):
        if not isinstance(messages, list):
            messages = [messages]

        sent_messages_tokens = []

        for message in messages:
            token = self._message_sender.post_to_public_account(
                sender, self._bot_configuration.name,
                self._bot_configuration.avatar, message)
            sent_messages_tokens.append(token)

        return sent_messages_tokens

    def _calculate_message_signature(self, message):
        return hmac.new(
         bytes(self._bot_configuration.auth_token.encode('ascii')),
         msg=message,
         digestmod=hashlib.sha256)\
         .hexdigest()