Beispiel #1
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)
def test_get_online_missing_ids(monkeypatch):
    monkeypatch.setattr("requests.post", stub)
    request_sender = ApiRequestSender(logging.getLogger(), VIBER_BOT_API_URL,
                                      VIBER_BOT_CONFIGURATION,
                                      VIBER_BOT_USER_AGENT)

    with pytest.raises(Exception) as exc:
        request_sender.get_online_status(ids=None)

        assert exc.value.message.startswith(
            "missing parameter ids, should be a list of viber memberIds")
def test_get_user_details_success(monkeypatch):
    def callback(endpoint, data, headers):
        request = json.loads(data)
        assert endpoint == VIBER_BOT_API_URL + "/" + BOT_API_ENDPOINT.GET_USER_DETAILS
        assert request['auth_token'] == VIBER_BOT_CONFIGURATION.auth_token
        response = Stub()
        response.raise_for_status = stub
        response.text = "{\"status\": 0, \"status_message\": \"OK\", \"user\": {}}"

        return response

    monkeypatch.setattr("requests.post", callback)
    request_sender = ApiRequestSender(logging.getLogger(), VIBER_BOT_API_URL,
                                      VIBER_BOT_CONFIGURATION,
                                      VIBER_BOT_USER_AGENT)

    request_sender.get_user_details(user_id="03249305A=")
def test_post_request_success(monkeypatch):
    def callback(endpoint, data, headers):
        request = json.loads(data)
        assert endpoint == VIBER_BOT_API_URL + "/" + BOT_API_ENDPOINT.GET_ACCOUNT_INFO
        assert request['auth_token'] == VIBER_BOT_CONFIGURATION.auth_token
        assert headers['User-Agent'] == VIBER_BOT_USER_AGENT
        response = Stub()
        response.raise_for_status = stub
        response.text = "{}"

        return response

    monkeypatch.setattr("requests.post", callback)

    request_sender = ApiRequestSender(logging.getLogger(), VIBER_BOT_API_URL,
                                      VIBER_BOT_CONFIGURATION,
                                      VIBER_BOT_USER_AGENT)
    request_sender.get_account_info()
def test_set_webhook_failure():
    webhook_events = [
        EventType.DELIVERED, EventType.UNSUBSCRIBED, EventType.SEEN
    ]
    url = "http://sample.url.com"

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

    request_sender = ApiRequestSender(logging.getLogger(), VIBER_BOT_API_URL,
                                      VIBER_BOT_CONFIGURATION,
                                      VIBER_BOT_USER_AGENT)
    request_sender.post_request = post_request
    with pytest.raises(Exception) as exc:
        request_sender.set_webhook(url=url, webhook_events=webhook_events)

        assert exc.value.message.startswith(
            "failed with status: 1, message: failed")
def test_set_webhook_sanity():
    webhook_events = [
        EventType.DELIVERED, EventType.UNSUBSCRIBED, EventType.SEEN
    ]
    url = "http://sample.url.com"

    def post_request(endpoint, payload):
        request = json.loads(payload)
        assert endpoint == BOT_API_ENDPOINT.SET_WEBHOOK
        assert request['auth_token'] == VIBER_BOT_CONFIGURATION.auth_token
        assert request['event_types'] == webhook_events
        assert request['url'] == url
        return dict(status=0, event_types=webhook_events)

    request_sender = ApiRequestSender(logging.getLogger(), VIBER_BOT_API_URL,
                                      VIBER_BOT_CONFIGURATION,
                                      VIBER_BOT_USER_AGENT)
    request_sender.post_request = post_request

    request_sender.set_webhook(url=url, webhook_events=webhook_events)
def test_get_online_status_fail(monkeypatch):
    def callback(endpoint, data, headers):
        request = json.loads(data)
        assert endpoint == VIBER_BOT_API_URL + "/" + BOT_API_ENDPOINT.GET_ONLINE
        assert request['auth_token'] == VIBER_BOT_CONFIGURATION.auth_token
        assert headers['User-Agent'] == VIBER_BOT_USER_AGENT
        response = Stub()
        response.raise_for_status = stub
        response.text = "{\"status\": 1, \"status_message\": \"fail\"}"

        return response

    monkeypatch.setattr("requests.post", callback)
    request_sender = ApiRequestSender(logging.getLogger(), VIBER_BOT_API_URL,
                                      VIBER_BOT_CONFIGURATION,
                                      VIBER_BOT_USER_AGENT)

    with pytest.raises(Exception) as exc:
        request_sender.get_online_status(ids=["0123456789="])

        assert exc.value.message.startswith("failed with status:")
Beispiel #8
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()
Beispiel #9
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):
        self._logger.debug(u"setting webhook to url: {0}".format(url))
        return self._request_sender.set_webhook(url, webhook_events)

    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)
        request = create_request(request_dict)
        self._logger.debug(u"parsed request={0}".format(request))
        return request

    def send(self, method, messages, *args):
        if not isinstance(messages, list):
            messages = [messages]

        sent_messages_tokens = []

        for message in messages:
            token = method(self._bot_configuration.name, self._bot_configuration.avatar, message, *args)
            sent_messages_tokens.append(token)

        return sent_messages_tokens

    def send_messages(self, to, messages):
        """
        :param to: Viber user id
        :param messages: list of Message objects to be sent
        :return: list of tokens of the sent messages
        """
        self._logger.debug("going to send messages: {0}, to: {1}".format(messages, to))
        return self.send(self._message_sender.send_message, messages, to)

    def post(self, from_admin, messages):
        """
        :param from_admin: Unique Viber user ID of one of the accounts admins. 
        A list of admins and IDs is available in get_account_info response
        :param messages: list of Message objects to be sent
        :return: list of tokens of the sent messages
        """
        self._logger.debug("going to post messages to public chat: {0}, from: {1}".format(messages, from_admin))
        return self.send(self._message_sender.post, messages, from_admin)

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