diff --git a/MIGRATION.md b/MIGRATION.md index 892a4f5f9..495b50c8a 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -2,9 +2,9 @@ Starting with version 3.x, the LINE Bot SDK for Python provides a new set of modules under `linebot.v3`. These modules are auto-generated from the [LINE OpenAPI spec](https://github.com/line/line-openapi), making it easy to keep up with future API changes. -The v3 modules are **not backward-compatible** with the previous `linebot` modules, but both coexist in the same package. This means you can migrate your code incrementally — one file or one endpoint at a time. +The v3 modules are **not backward-compatible** with the previous `linebot` modules. The legacy (v2) modules have been removed — only `linebot.v3` is available. -> **Note:** Only `linebot.v3` will be maintained going forward. The previous `linebot` modules (v2) will not receive updates. +> **Note:** If you are still using v2 imports such as `from linebot import LineBotApi`, you must migrate them before upgrading. This guide walks through the migration step by step. ## Table of Contents @@ -22,7 +22,6 @@ The v3 modules are **not backward-compatible** with the previous `linebot` modul - [Method mapping](#method-mapping) - [Error handling](#error-handling) - [Response headers / x-line-request-id](#response-headers--x-line-request-id) -- [Suppressing deprecation warnings](#suppressing-deprecation-warnings) --- @@ -34,7 +33,7 @@ The v3 modules are **not backward-compatible** with the previous `linebot` modul pip install line-bot-sdk>=3.0 ``` -Both the deprecated `linebot` modules and the new `linebot.v3` modules are included — no need to install a separate package. +The legacy `linebot` modules have been removed. Only the `linebot.v3` modules are included in the package. ### 2. Replace client construction @@ -734,18 +733,3 @@ response = line_bot_api.reply_message_with_http_info( print(response.status_code) # HTTP status code print(response.headers.get('x-line-request-id')) # Request ID ``` - ---- - -## Suppressing deprecation warnings - -During migration, you may see deprecation warnings when using the old `linebot` modules. To suppress them: - -```python -import warnings -from linebot import LineBotSdkDeprecatedIn30 - -warnings.filterwarnings("ignore", category=LineBotSdkDeprecatedIn30) -``` - -> **Tip:** Only suppress these warnings temporarily. Once your migration is complete, remove both the warning filter and the deprecated imports. diff --git a/README.rst b/README.rst index fa8d07a83..2d31ace14 100644 --- a/README.rst +++ b/README.rst @@ -350,39 +350,11 @@ LINE's SDK developer team decided to generate SDK code based on OpenAPI spec. ht As a result, LINE bot sdk 3.x is not compatible with 2.x. It can follow the future API changes very quickly. -We will be maintaining only ``linebot.v3`` going forward. -To utilize the latest features, we recommend you gradually transition to ``linebot.v3`` modules in your application, although you can still continue to use the 2.x ``linebot`` modules. - -While we won't update ``linebot`` modules anymore, users can still continue to use the version 2.x ``linebot`` modules. -We also welcome pull requests for the version ``2.x`` and ``3.x`` modules. +The legacy ``linebot`` (v2) modules have been removed. Only ``linebot.v3`` is supported. For a step-by-step migration guide with before/after examples, see `MIGRATION.md `__. -How to suppress deprecation warnings ------------------------------------- -If you keep using old line-bot-sdk library (``version < 3.x``) but use ``3.x``, you'll get - -:: - - LineBotSdkDeprecatedIn30: Call to deprecated method get_bot_info. (Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_bot_info(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.) -- Deprecated since version 3.0.0. - - -If it's noisy, you can suppress this warning as follows. - - -.. code:: python - - import warnings - from linebot import LineBotSdkDeprecatedIn30 - - ## your code here - ... - - if __name__ == '__main__': - warnings.filterwarnings("ignore", category=LineBotSdkDeprecatedIn30) - - Contributing ------------ Please check `CONTRIBUTING `__ before making a contribution. diff --git a/docs/source/index.rst b/docs/source/index.rst index 58c363324..72afabc09 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -12,7 +12,6 @@ Contents: :maxdepth: 4 linebot.v3 - linebot Indices and tables diff --git a/docs/source/linebot.models.rst b/docs/source/linebot.models.rst deleted file mode 100644 index 29885e9e9..000000000 --- a/docs/source/linebot.models.rst +++ /dev/null @@ -1,97 +0,0 @@ -linebot.models package (deprecated) -==================================== - -.. warning:: - - **Deprecated.** Use :doc:`linebot.v3 ` instead. - -linebot.models.actions module ------------------------------- - -.. automodule:: linebot.models.actions - :exclude-members: get_action, get_actions - -linebot.models.base module --------------------------- - -.. automodule:: linebot.models.base - -linebot.models.error module ---------------------------- - -.. automodule:: linebot.models.error - -linebot.models.events module ----------------------------- - -.. automodule:: linebot.models.events - -linebot.models.filter module ------------------------------------ - -.. automodule:: linebot.models.filter - -linebot.models.flex_message module ------------------------------------ - -.. automodule:: linebot.models.flex_message - -linebot.models.imagemap module ------------------------------- - -.. automodule:: linebot.models.imagemap - -linebot.models.insight module ------------------------------- - -.. automodule:: linebot.models.insight - -linebot.models.limit module ------------------------------- - -.. automodule:: linebot.models.limit - -linebot.models.messages module ------------------------------- - -.. automodule:: linebot.models.messages - -linebot.models.operator module -------------------------------- - -.. automodule:: linebot.models.operator - -linebot.models.recipient module -------------------------------- - -.. automodule:: linebot.models.recipient - -linebot.models.responses module -------------------------------- - -.. automodule:: linebot.models.responses - -linebot.models.rich_menu module -------------------------------- - -.. automodule:: linebot.models.rich_menu - -linebot.models.send_messages module ------------------------------------ - -.. automodule:: linebot.models.send_messages - -linebot.models.sources module ------------------------------ - -.. automodule:: linebot.models.sources - -linebot.models.template module ------------------------------- - -.. automodule:: linebot.models.template - -linebot.models.things module ------------------------------- - -.. automodule:: linebot.models.things diff --git a/docs/source/linebot.rst b/docs/source/linebot.rst deleted file mode 100644 index 1bcb8c221..000000000 --- a/docs/source/linebot.rst +++ /dev/null @@ -1,34 +0,0 @@ -linebot package (deprecated) -============================ - -.. warning:: - - **Deprecated.** Use :doc:`linebot.v3 ` instead. - -linebot.api module ------------------- - -.. automodule:: linebot.api - -linebot.webhook module ----------------------- - -.. automodule:: linebot.webhook - :exclude-members: compare_digest - -linebot.exceptions module -------------------------- - -.. automodule:: linebot.exceptions - -linebot.http_client module --------------------------- - -.. automodule:: linebot.http_client - -Subpackages ------------ - -.. toctree:: - - linebot.models diff --git a/linebot/__init__.py b/linebot/__init__.py index a3db7da98..64d89b53b 100644 --- a/linebot/__init__.py +++ b/linebot/__init__.py @@ -18,29 +18,3 @@ from .__about__ import ( # noqa __version__ ) -from .api import ( # noqa - LineBotApi, -) -from .async_api import ( # noqa - AsyncLineBotApi, -) -from .http_client import ( # noqa - HttpClient, - RequestsHttpClient, - HttpResponse, -) -from .async_http_client import ( # noqa - AsyncHttpClient, - AsyncHttpResponse, -) -from .webhook import ( # noqa - SignatureValidator, - WebhookParser, - WebhookHandler, - WebhookPayload, -) - -from .deprecations import ( - LineBotSdkDeprecationWarning, - LineBotSdkDeprecatedIn30, -) diff --git a/linebot/aiohttp_async_http_client.py b/linebot/aiohttp_async_http_client.py deleted file mode 100644 index e425c46ba..000000000 --- a/linebot/aiohttp_async_http_client.py +++ /dev/null @@ -1,164 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.aiohttp_async_http_client module.""" - -from linebot import AsyncHttpClient, AsyncHttpResponse - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'linebot.v3' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AiohttpAsyncHttpClient(AsyncHttpClient): - """HttpClient implemented by requests.""" - - def __init__(self, session, timeout=AsyncHttpClient.DEFAULT_TIMEOUT): - """__init__ method. - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`DEFAULT_TIMEOUT` - :type timeout: float | tuple(float, float) - """ - super(AiohttpAsyncHttpClient, self).__init__(timeout) - self.session = session - - async def get(self, url, headers=None, params=None, timeout=None): - """GET request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param dict params: (optional) Request query parameter - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: :py:class:`AsyncHttpResponse` - :return: AsyncHttpResponse instance - """ - if timeout is None: - timeout = self.timeout - - response = await self.session.get(url, headers=headers, params=params, timeout=timeout) - return AiohttpAsyncHttpResponse(response) - - async def post(self, url, headers=None, data=None, timeout=None): - """POST request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param data: (optional) Dictionary, bytes, or file-like object to send in the body - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: :py:class:`AiohttpAsyncHttpResponse` - :return: AiohttpAsyncHttpResponse instance - """ - if timeout is None: - timeout = self.timeout - - response = await self.session.post(url, headers=headers, data=data, timeout=timeout) - return AiohttpAsyncHttpResponse(response) - - async def delete(self, url, headers=None, data=None, timeout=None): - """DELETE request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param data: (optional) Dictionary, bytes, or file-like object to send in the body - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: :py:class:`AiohttpAsyncHttpResponse` - :return: AiohttpAsyncHttpResponse instance - """ - if timeout is None: - timeout = self.timeout - - response = await self.session.delete(url, headers=headers, data=data, timeout=timeout) - return AiohttpAsyncHttpResponse(response) - - async def put(self, url, headers=None, data=None, timeout=None): - """PUT request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param data: (optional) Dictionary, bytes, or file-like object to send in the body - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: :py:class:`AiohttpAsyncHttpResponse` - :return: AiohttpAsyncHttpResponse instance - """ - if timeout is None: - timeout = self.timeout - - response = await self.session.put(url, headers=headers, data=data, timeout=timeout) - return AiohttpAsyncHttpResponse(response) - - -@deprecated(reason="Use 'linebot.v3' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AiohttpAsyncHttpResponse(AsyncHttpResponse): - """AsyncHttpResponse implemented by aiohttp's response.""" - - def __init__(self, response): - """__init__ method. - - :param response: aiohttp's response - """ - self.response = response - - @property - def status_code(self): - """Get status code.""" - return self.response.status - - @property - def headers(self): - """Get headers. - - :rtype :py:class:`aiohttp.multidict.CIMultiDictProxy` - """ - return self.response.headers - - @property - async def text(self): - """Get response body as text-decoded.""" - return await self.response.text() - - @property - async def content(self): - """Get response body as binary.""" - return await self.response.content.read() - - @property - async def json(self): - """Get response body as json-decoded.""" - return await self.response.json() - - def iter_content(self, chunk_size=1024): - """Get response body as iterator content (stream). - - :param int chunk_size: - """ - return self.response.content.iter_chunked(chunk_size) diff --git a/linebot/api.py b/linebot/api.py deleted file mode 100644 index 05bd2afbb..000000000 --- a/linebot/api.py +++ /dev/null @@ -1,2158 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.api module.""" - -import json - -from .__about__ import __version__ -from .exceptions import LineBotApiError -from .http_client import HttpClient, RequestsHttpClient -from .models import ( - Error, Profile, MemberIds, Content, RichMenuResponse, MessageQuotaResponse, - MessageQuotaConsumptionResponse, IssueLinkTokenResponse, IssueChannelTokenResponse, - MessageDeliveryBroadcastResponse, MessageDeliveryMulticastResponse, - MessageDeliveryPushResponse, MessageDeliveryReplyResponse, - InsightMessageDeliveryResponse, InsightFollowersResponse, InsightDemographicResponse, - InsightMessageEventResponse, BroadcastResponse, NarrowcastResponse, - MessageProgressNarrowcastResponse, BotInfo, GetWebhookResponse, TestWebhookResponse, - AudienceGroup, ClickAudienceGroup, ImpAudienceGroup, GetAuthorityLevel, Audience, - CreateAudienceGroup -) -from .models.responses import ( - Group, UserIds, RichMenuAliasResponse, RichMenuAliasListResponse, ChannelAccessTokens, - IssueChannelTokenResponseV2, VerifyChannelTokenResponseV2, ValidAccessTokenKeyIDsResponse, - InsightMessageEventOfCustomAggregationUnitResponse, AggregationInfoResponse, - AggregationNameListResponse, - ValidateBroadcastMessageObjectsResponse, - ValidateMulticastMessageObjectsResponse, ValidateNarrowcastMessageObjectsResponse, - ValidatePushMessageObjectsResponse, ValidateReplyMessageObjectsResponse, -) -from .deprecations import ( - LineBotSdkDeprecatedIn30 -) - -from deprecated import deprecated - - -@deprecated(reason="Use 'from linebot.v3 import LineBotClient'. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class LineBotApi(object): - """LineBotApi provides interface for LINE messaging API.""" - - DEFAULT_API_ENDPOINT = 'https://api.line.me' - DEFAULT_API_DATA_ENDPOINT = 'https://api-data.line.me' - - def __init__(self, channel_access_token, - endpoint=DEFAULT_API_ENDPOINT, data_endpoint=DEFAULT_API_DATA_ENDPOINT, - timeout=HttpClient.DEFAULT_TIMEOUT, http_client=RequestsHttpClient): - """__init__ method. - - :param str channel_access_token: Your channel access token - :param str endpoint: (optional) Default is https://api.line.me - :param str data_endpoint: (optional) Default is https://api-data.line.me - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is linebot.http_client.HttpClient.DEFAULT_TIMEOUT - :type timeout: float | tuple(float, float) - :param http_client: (optional) Default is - :py:class:`linebot.http_client.RequestsHttpClient` - :type http_client: T <= :py:class:`linebot.http_client.HttpClient` - """ - self.data_endpoint = data_endpoint - self.endpoint = endpoint - self.headers = { - 'Authorization': 'Bearer ' + channel_access_token, - 'User-Agent': 'line-bot-sdk-python/' + __version__ - } - - if http_client: - self.http_client = http_client(timeout=timeout) - else: - self.http_client = RequestsHttpClient(timeout=timeout) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).reply_message(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def reply_message(self, reply_token, messages, notification_disabled=False, timeout=None): - """Call reply message API. - - https://developers.line.biz/en/reference/messaging-api/#send-reply-message - - Respond to events from users, groups, and rooms. - - Webhooks are used to notify you when an event occurs. - For events that you can respond to, a replyToken is issued for replying to messages. - - Because the replyToken becomes invalid after a certain period of time, - responses should be sent as soon as a message is received. - - Reply tokens can only be used once. - - :param str reply_token: replyToken received via webhook - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param bool notification_disabled: (optional) True to disable push notification - when the message is sent. The default value is False. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - data = { - 'replyToken': reply_token, - 'messages': [message.as_json_dict() for message in messages], - 'notificationDisabled': notification_disabled, - } - - self._post( - '/v2/bot/message/reply', data=json.dumps(data), timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).push_message(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def push_message( - self, to, messages, - retry_key=None, notification_disabled=False, - custom_aggregation_units=None, timeout=None): - """Call push message API. - - https://developers.line.biz/en/reference/messaging-api/#send-push-message - - Send messages to users, groups, and rooms at any time. - - :param str to: ID of the receiver - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param retry_key: (optional) Arbitrarily generated UUID in hexadecimal notation. - :param bool notification_disabled: (optional) True to disable push notification - when the message is sent. The default value is False. - :param custom_aggregation_units: (optional) Name of aggregation unit. Case-sensitive. - Max unit: 1 - Max aggregation unit name length: 30 characters - Supported character types: Half-width alphanumeric characters and underscore - :type custom_aggregation_units: str | list[str] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - if retry_key: - self.headers['X-Line-Retry-Key'] = retry_key - - data = { - 'to': to, - 'messages': [message.as_json_dict() for message in messages], - 'notificationDisabled': notification_disabled, - } - - if custom_aggregation_units is not None: - if not isinstance(custom_aggregation_units, (list, tuple)): - custom_aggregation_units = [custom_aggregation_units] - data['customAggregationUnits'] = custom_aggregation_units - - self._post( - '/v2/bot/message/push', data=json.dumps(data), timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).multicast(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def multicast(self, to, messages, retry_key=None, notification_disabled=False, - custom_aggregation_units=None, timeout=None): - """Call multicast API. - - https://developers.line.biz/en/reference/messaging-api/#send-multicast-message - - Sends push messages to multiple users at any time. - Messages cannot be sent to groups or rooms. - - :param to: IDs of the receivers - Max: 500 users - :type to: list[str] - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param retry_key: (optional) Arbitrarily generated UUID in hexadecimal notation. - :param bool notification_disabled: (optional) True to disable push notification - when the message is sent. The default value is False. - :param custom_aggregation_units: (optional) Name of aggregation unit. Case-sensitive. - Max unit: 1 - Max aggregation unit name length: 30 characters - Supported character types: Half-width alphanumeric characters and underscore - :type custom_aggregation_units: str | list[str] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - if retry_key: - self.headers['X-Line-Retry-Key'] = retry_key - - data = { - 'to': to, - 'messages': [message.as_json_dict() for message in messages], - 'notificationDisabled': notification_disabled, - } - - if custom_aggregation_units is not None: - if not isinstance(custom_aggregation_units, (list, tuple)): - custom_aggregation_units = [custom_aggregation_units] - data['customAggregationUnits'] = custom_aggregation_units - - self._post( - '/v2/bot/message/multicast', data=json.dumps(data), timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).broadcast(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def broadcast(self, messages, retry_key=None, notification_disabled=False, timeout=None): - """Call broadcast API. - - https://developers.line.biz/en/reference/messaging-api/#send-broadcast-message - - Sends push messages to multiple users at any time. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param retry_key: (optional) Arbitrarily generated UUID in hexadecimal notation. - :param bool notification_disabled: (optional) True to disable push notification - when the message is sent. The default value is False. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.BroadcastResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - if retry_key: - self.headers['X-Line-Retry-Key'] = retry_key - - data = { - 'messages': [message.as_json_dict() for message in messages], - 'notificationDisabled': notification_disabled, - } - - response = self._post( - '/v2/bot/message/broadcast', data=json.dumps(data), timeout=timeout - ) - - return BroadcastResponse(request_id=response.headers.get('X-Line-Request-Id')) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).narrowcast(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def narrowcast( - self, messages, - retry_key=None, recipient=None, filter=None, limit=None, - notification_disabled=False, timeout=None): - """Call narrowcast API. - - https://developers.line.biz/en/reference/messaging-api/#send-narrowcast-message - - Sends push messages to multiple users at any time. - Messages cannot be sent to groups or rooms. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param retry_key: (optional) Arbitrarily generated UUID in hexadecimal notation. - :param recipient: audience object of recipient - :type recipient: T <= :py:class:`linebot.models.recipient.AudienceRecipient` - :param filter: demographic filter of recipient - :type filter: T <= :py:class:`linebot.models.filter.DemographicFilter` - :param limit: limit on this narrowcast - :type limit: T <= :py:class:`linebot.models.limit.Limit` - :param bool notification_disabled: (optional) True to disable push notification - when the message is sent. The default value is False. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.NarrowcastResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - if retry_key: - self.headers['X-Line-Retry-Key'] = retry_key - - data = { - 'messages': [message.as_json_dict() for message in messages], - 'recipient': recipient.as_json_dict(), - 'filter': filter.as_json_dict(), - 'limit': limit.as_json_dict(), - 'notificationDisabled': notification_disabled, - } - - response = self._post( - '/v2/bot/message/narrowcast', data=json.dumps(data), timeout=timeout - ) - - return NarrowcastResponse(request_id=response.headers.get('X-Line-Request-Id')) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_narrowcast_progress(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_progress_status_narrowcast(self, request_id, timeout=None): - """Get progress status of narrowcast messages sent. - - https://developers.line.biz/en/reference/messaging-api/#get-narrowcast-progress-status - - Gets the number of messages sent with the /bot/message/progress/narrowcast endpoint. - - :param str request_id: request ID of narrowcast. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageDeliveryBroadcastResponse` - """ - response = self._get( - '/v2/bot/message/progress/narrowcast?requestId={request_id}'.format( - request_id=request_id), - timeout=timeout - ) - - return MessageProgressNarrowcastResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).validate_reply(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def validate_reply_message_objects(self, messages, timeout=None): - """Call validate reply message objects API. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-reply-message - - You can validate that an array of message objects is valid as a value - for the messages property of the request body for the send reply message endpoint. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.ValidateReplyMessageObjectsResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - data = { - 'messages': [message.as_json_dict() for message in messages], - } - - response = self._post( - '/v2/bot/message/validate/reply', data=json.dumps(data), - timeout=timeout - ) - - return ValidateReplyMessageObjectsResponse( - request_id=response.headers.get('X-Line-Request-Id')) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).validate_push(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def validate_push_message_objects(self, messages, timeout=None): - """Call validate push message objects API. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-push-message - - You can validate that an array of message objects is valid as a value - for the messages property of the request body for the send push message endpoint. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.ValidatePushMessageObjectsResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - data = { - 'messages': [message.as_json_dict() for message in messages], - } - - response = self._post( - '/v2/bot/message/validate/push', data=json.dumps(data), - timeout=timeout - ) - - return ValidatePushMessageObjectsResponse( - request_id=response.headers.get('X-Line-Request-Id')) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).validate_multicast(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def validate_multicast_message_objects(self, messages, timeout=None): - """Call validate multicast message objects API. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-multicast-message - - You can validate that an array of message objects is valid as a value - for the messages property of the request body for the send multicast message endpoint. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.ValidateMulticastMessageObjectsResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - data = { - 'messages': [message.as_json_dict() for message in messages], - } - - response = self._post( - '/v2/bot/message/validate/multicast', data=json.dumps(data), - timeout=timeout - ) - - return ValidateMulticastMessageObjectsResponse( - request_id=response.headers.get('X-Line-Request-Id')) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).validate_broadcast(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def validate_broadcast_message_objects(self, messages, timeout=None): - """Call validate broadcast message objects API. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-broadcast-message - - You can validate that an array of message objects is valid as a value - for the messages property of the request body for the send broadcast message endpoint. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.ValidateBroadcastMessageObjectsResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - data = { - 'messages': [message.as_json_dict() for message in messages], - } - - response = self._post( - '/v2/bot/message/validate/broadcast', data=json.dumps(data), - timeout=timeout - ) - - return ValidateBroadcastMessageObjectsResponse( - request_id=response.headers.get('X-Line-Request-Id')) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).validate_narrowcast(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def validate_narrowcast_message_objects(self, messages, timeout=None): - """Call validate narrowcast message objects API. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-narrowcast-message - - You can validate that an array of message objects is valid as a value - for the messages property of the request body for the send narrowcast message endpoint. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.ValidateNarrowcastMessageObjectsResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - data = { - 'messages': [message.as_json_dict() for message in messages], - } - - response = self._post( - '/v2/bot/message/validate/narrowcast', data=json.dumps(data), - timeout=timeout - ) - - return ValidateNarrowcastMessageObjectsResponse( - request_id=response.headers.get('X-Line-Request-Id')) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_number_of_sent_broadcast_messages(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_message_delivery_broadcast(self, date, timeout=None): - """Get number of sent broadcast messages. - - https://developers.line.biz/en/reference/messaging-api/#get-number-of-broadcast-messages - - Gets the number of messages sent with the /bot/message/broadcast endpoint. - - :param str date: Date the messages were sent. The format is `yyyyMMdd` (Timezone is UTC+9). - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageDeliveryBroadcastResponse` - """ - response = self._get( - '/v2/bot/message/delivery/broadcast?date={date}'.format(date=date), - timeout=timeout - ) - - return MessageDeliveryBroadcastResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_number_of_sent_reply_messages(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_message_delivery_reply(self, date, timeout=None): - """Get number of sent reply messages. - - https://developers.line.biz/en/reference/messaging-api/#get-number-of-reply-messages - - Gets the number of messages sent with the /bot/message/reply endpoint. - - :param str date: Date the messages were sent. The format is `yyyyMMdd` (Timezone is UTC+9). - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageDeliveryReplyResponse` - """ - response = self._get( - '/v2/bot/message/delivery/reply?date={date}'.format(date=date), - timeout=timeout - ) - - return MessageDeliveryReplyResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_number_of_sent_push_messages(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_message_delivery_push(self, date, timeout=None): - """Get number of sent push messages. - - https://developers.line.biz/en/reference/messaging-api/#get-number-of-push-messages - - Gets the number of messages sent with the /bot/message/push endpoint. - - :param str date: Date the messages were sent. The format is `yyyyMMdd` (Timezone is UTC+9). - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageDeliveryPushResponse` - """ - response = self._get( - '/v2/bot/message/delivery/push?date={date}'.format(date=date), - timeout=timeout - ) - - return MessageDeliveryPushResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_number_of_sent_multicast_messages(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_message_delivery_multicast(self, date, timeout=None): - """Get number of sent multicast messages. - - https://developers.line.biz/en/reference/messaging-api/#get-number-of-multicast-messages - - Gets the number of messages sent with the /bot/message/multicast endpoint. - - :param str date: Date the messages were sent. The format is `yyyyMMdd` (Timezone is UTC+9). - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageDeliveryMulticastResponse` - """ - response = self._get( - '/v2/bot/message/delivery/multicast?date={date}'.format(date=date), - timeout=timeout - ) - - return MessageDeliveryMulticastResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_profile(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_profile(self, user_id, timeout=None): - """Call get profile API. - - https://developers.line.biz/en/reference/messaging-api/#get-profile - - Get user profile information. - - :param str user_id: User ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Profile` - :return: Profile instance - """ - response = self._get( - '/v2/bot/profile/{user_id}'.format(user_id=user_id), - timeout=timeout - ) - - return Profile.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_group_summary(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_group_summary(self, group_id, timeout=None): - """Call get group summary API. - - https://developers.line.biz/en/reference/messaging-api/#get-group-summary - - Gets the group ID, group name, and group icon URL of a group - where the LINE Official Account is a member. - - :param str group_id: Group ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Group` - :return: Profile instance - """ - response = self._get( - '/v2/bot/group/{group_id}/summary'.format(group_id=group_id), - timeout=timeout - ) - - return Group.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_group_member_count(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_group_members_count(self, group_id, timeout=None): - """Call get members in group count API. - - https://developers.line.biz/en/reference/messaging-api/#get-members-group-count - - Gets the count of members in a group. - - :param str group_id: Group ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Group` - :return: Profile instance - """ - response = self._get( - '/v2/bot/group/{group_id}/members/count'.format(group_id=group_id), - timeout=timeout - ) - - return response.json.get('count') - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_room_member_count(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_room_members_count(self, room_id, timeout=None): - """Call get members in room count API. - - https://developers.line.biz/en/reference/messaging-api/#get-members-room-count - - Gets the count of members in a room. - - :param str room_id: Room ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Group` - :return: Profile instance - """ - response = self._get( - '/v2/bot/room/{room_id}/members/count'.format(room_id=room_id), - timeout=timeout - ) - - return response.json.get('count') - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_group_member_profile(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_group_member_profile(self, group_id, user_id, timeout=None): - """Call get group member profile API. - - https://developers.line.biz/en/reference/messaging-api/#get-group-member-profile - - Gets the user profile of a member of a group that - the bot is in. This can be the user ID of a user who has - not added the bot as a friend or has blocked the bot. - - :param str group_id: Group ID - :param str user_id: User ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Profile` - :return: Profile instance - """ - response = self._get( - '/v2/bot/group/{group_id}/member/{user_id}'.format(group_id=group_id, user_id=user_id), - timeout=timeout - ) - - return Profile.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_room_member_profile(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_room_member_profile(self, room_id, user_id, timeout=None): - """Call get room member profile API. - - https://developers.line.biz/en/reference/messaging-api/#get-room-member-profile - - Gets the user profile of a member of a room that - the bot is in. This can be the user ID of a user who has - not added the bot as a friend or has blocked the bot. - - :param str room_id: Room ID - :param str user_id: User ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Profile` - :return: Profile instance - """ - response = self._get( - '/v2/bot/room/{room_id}/member/{user_id}'.format(room_id=room_id, user_id=user_id), - timeout=timeout - ) - - return Profile.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_group_members_ids(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_group_member_ids(self, group_id, start=None, timeout=None): - """Call get group member IDs API. - - https://developers.line.biz/en/reference/messaging-api/#get-group-member-ids - - Gets the user IDs of the members of a group that the bot is in. - This includes the user IDs of users who have not added the bot as a friend - or has blocked the bot. - - :param str group_id: Group ID - :param str start: continuationToken - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MemberIds` - :return: MemberIds instance - """ - params = None if start is None else {'start': start} - - response = self._get( - '/v2/bot/group/{group_id}/members/ids'.format(group_id=group_id), - params=params, - timeout=timeout - ) - - return MemberIds.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_room_members_ids(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_room_member_ids(self, room_id, start=None, timeout=None): - """Call get room member IDs API. - - https://developers.line.biz/en/reference/messaging-api/#get-room-member-ids - - Gets the user IDs of the members of a group that the bot is in. - This includes the user IDs of users who have not added the bot as a friend - or has blocked the bot. - - :param str room_id: Room ID - :param str start: continuationToken - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MemberIds` - :return: MemberIds instance - """ - params = None if start is None else {'start': start} - - response = self._get( - '/v2/bot/room/{room_id}/members/ids'.format(room_id=room_id), - params=params, - timeout=timeout - ) - - return MemberIds.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_message_content(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_message_content(self, message_id, timeout=None): - """Call get content API. - - https://developers.line.biz/en/reference/messaging-api/#get-content - - Retrieve image, video, and audio data sent by users. - - :param str message_id: Message ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Content` - :return: Content instance - """ - response = self._get( - '/v2/bot/message/{message_id}/content'.format(message_id=message_id), - endpoint=self.data_endpoint, stream=True, timeout=timeout - ) - - return Content(response) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).leave_group(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def leave_group(self, group_id, timeout=None): - """Call leave group API. - - https://developers.line.biz/en/reference/messaging-api/#leave-group - - Leave a group. - - :param str group_id: Group ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._post( - '/v2/bot/group/{group_id}/leave'.format(group_id=group_id), - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).leave_room(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def leave_room(self, room_id, timeout=None): - """Call leave room API. - - https://developers.line.biz/en/reference/messaging-api/#leave-room - - Leave a room. - - :param str room_id: Room ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._post( - '/v2/bot/room/{room_id}/leave'.format(room_id=room_id), - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_rich_menu(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_rich_menu(self, rich_menu_id, timeout=None): - """Call get rich menu API. - - https://developers.line.biz/en/reference/messaging-api/#get-rich-menu - - :param str rich_menu_id: ID of the rich menu - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.RichMenuResponse` - :return: RichMenuResponse instance - """ - response = self._get( - '/v2/bot/richmenu/{rich_menu_id}'.format(rich_menu_id=rich_menu_id), - timeout=timeout - ) - - return RichMenuResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_rich_menu_alias(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_rich_menu_alias(self, rich_menu_alias_id=None, timeout=None): - """Call get rich menu alias API. - - https://developers.line.biz/en/reference/messaging-api/#get-rich-menu-alias-by-id - - :param str rich_menu_alias_id: ID of an uploaded rich menu alias. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.RichMenuAliasResponse` - :return: RichMenuAliasResponse instance - """ - response = self._get( - '/v2/bot/richmenu/alias/{rich_menu_id}'.format(rich_menu_id=rich_menu_alias_id), - timeout=timeout - ) - return RichMenuAliasResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_rich_menu_alias_list(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_rich_menu_alias_list(self, timeout=None): - """Call get rich menu alias list API. - - https://developers.line.biz/en/reference/messaging-api/#update-rich-menu-alias - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.RichMenuAliasListResponse` - :return: RichMenuAliasListResponse instance - """ - response = self._get( - '/v2/bot/richmenu/alias/list', - timeout=timeout - ) - return RichMenuAliasListResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).validate_rich_menu_object(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def validate_rich_menu_object(self, rich_menu, timeout=None): - """Call validate rich menu object API. - - https://developers.line.biz/ja/reference/messaging-api/#validate-rich-menu-object - - :param rich_menu: Inquired to validate a rich menu object. - :type rich_menu: T <= :py:class:`linebot.models.rich_menu.RichMenu` - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._post( - '/v2/bot/richmenu/validate', data=rich_menu.as_json_string(), - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).create_rich_menu(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def create_rich_menu(self, rich_menu, timeout=None): - """Call create rich menu API. - - https://developers.line.biz/en/reference/messaging-api/#create-rich-menu - - :param rich_menu: Inquired to create a rich menu object. - :type rich_menu: T <= :py:class:`linebot.models.rich_menu.RichMenu` - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: str - :return: rich menu id - """ - response = self._post( - '/v2/bot/richmenu', data=rich_menu.as_json_string(), timeout=timeout - ) - - return response.json.get('richMenuId') - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).create_rich_menu_alias(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def create_rich_menu_alias(self, rich_menu_alias, timeout=None): - """Call create rich menu alias API. - - https://developers.line.biz/en/reference/messaging-api/#create-rich-menu-alias - - :param rich_menu_alias: Inquired to create a rich menu alias object. - :type rich_menu_alias: T <= :py:class:`linebot.models.rich_menu.RichMenuAlias` - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: str - :return: rich menu id - """ - self._post( - '/v2/bot/richmenu/alias', data=rich_menu_alias.as_json_string(), timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).update_rich_menu_alias(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def update_rich_menu_alias(self, rich_menu_alias_id, rich_menu_alias, timeout=None): - """Call update rich menu alias API. - - https://developers.line.biz/en/reference/messaging-api/#update-rich-menu-alias - - :param str rich_menu_alias_id: ID of an uploaded rich menu alias. - :param rich_menu_alias: Inquired to create a rich menu alias object. - :type rich_menu_alias: T <= :py:class:`linebot.models.rich_menu.RichMenuAlias` - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: str - :return: rich menu id - """ - self._post( - '/v2/bot/richmenu/alias/{rich_menu_id}'.format(rich_menu_id=rich_menu_alias_id), - data=rich_menu_alias.as_json_string(), - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).delete_rich_menu(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def delete_rich_menu(self, rich_menu_id, timeout=None): - """Call delete rich menu API. - - https://developers.line.biz/en/reference/messaging-api/#delete-rich-menu - - :param str rich_menu_id: ID of an uploaded rich menu - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._delete( - '/v2/bot/richmenu/{rich_menu_id}'.format(rich_menu_id=rich_menu_id), - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).delete_rich_menu_alias(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def delete_rich_menu_alias(self, rich_menu_alias_id, timeout=None): - """Call delete rich menu alias API. - - https://developers.line.biz/en/reference/messaging-api/#delete-rich-menu-alias - - :param str rich_menu_alias_id: ID of an uploaded rich menu alias. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._delete( - '/v2/bot/richmenu/alias/{rich_menu_alias_id}'.format( - rich_menu_alias_id=rich_menu_alias_id), - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_rich_menu_id_of_user(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_rich_menu_id_of_user(self, user_id, timeout=None): - """Call get rich menu ID of user API. - - https://developers.line.biz/en/reference/messaging-api/#get-rich-menu-id-of-user - - :param str user_id: IDs of the user - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: str - :return: rich menu id - """ - response = self._get( - '/v2/bot/user/{user_id}/richmenu'.format(user_id=user_id), - timeout=timeout - ) - - return response.json.get('richMenuId') - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).link_rich_menu_id_to_user(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def link_rich_menu_to_user(self, user_id, rich_menu_id, timeout=None): - """Call link rich menu to user API. - - https://developers.line.biz/en/reference/messaging-api/#link-rich-menu-to-user - - :param str user_id: ID of the user - :param str rich_menu_id: ID of an uploaded rich menu - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._post( - '/v2/bot/user/{user_id}/richmenu/{rich_menu_id}'.format( - user_id=user_id, - rich_menu_id=rich_menu_id - ), - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).link_rich_menu_id_to_users(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def link_rich_menu_to_users(self, user_ids, rich_menu_id, timeout=None): - """Links a rich menu to multiple users. - - https://developers.line.biz/en/reference/messaging-api/#link-rich-menu-to-users - - :param user_ids: user IDs - Max: 150 users - :type user_ids: list[str] - :param str rich_menu_id: ID of an uploaded rich menu - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._post( - '/v2/bot/richmenu/bulk/link', - data=json.dumps({ - 'userIds': user_ids, - 'richMenuId': rich_menu_id, - }), - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).unlink_rich_menu_id_from_user(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def unlink_rich_menu_from_user(self, user_id, timeout=None): - """Call unlink rich menu from user API. - - https://developers.line.biz/en/reference/messaging-api#unlink-rich-menu-from-user - - :param str user_id: ID of the user - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._delete( - '/v2/bot/user/{user_id}/richmenu'.format(user_id=user_id), - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).unlink_rich_menu_id_from_users(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def unlink_rich_menu_from_users(self, user_ids, timeout=None): - """Unlinks rich menus from multiple users. - - https://developers.line.biz/en/reference/messaging-api/#unlink-rich-menu-from-users - - :param user_ids: user IDs - Max: 150 users - :type user_ids: list[str] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._post( - '/v2/bot/richmenu/bulk/unlink', - data=json.dumps({ - 'userIds': user_ids, - }), - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_rich_menu_image(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_rich_menu_image(self, rich_menu_id, timeout=None): - """Call download rich menu image API. - - https://developers.line.biz/en/reference/messaging-api#download-rich-menu-image - - :param str rich_menu_id: ID of the rich menu with the image to be downloaded - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Content` - :return: Content instance - """ - response = self._get( - '/v2/bot/richmenu/{rich_menu_id}/content'.format(rich_menu_id=rich_menu_id), - endpoint=self.data_endpoint, timeout=timeout - ) - - return Content(response) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).set_rich_menu_image(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def set_rich_menu_image(self, rich_menu_id, content_type, content, timeout=None): - """Call upload rich menu image API. - - https://developers.line.me/en/docs/messaging-api/reference/#upload-rich-menu-image - - Uploads and attaches an image to a rich menu. - - :param str rich_menu_id: IDs of the richmenu - :param str content_type: image/jpeg or image/png - :param content: image content as bytes, or file-like object - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._post( - '/v2/bot/richmenu/{rich_menu_id}/content'.format(rich_menu_id=rich_menu_id), - endpoint=self.data_endpoint, - data=content, - headers={'Content-Type': content_type}, - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_rich_menu_list(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_rich_menu_list(self, timeout=None): - """Call get rich menu list API. - - https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu-list - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: list(T <= :py:class:`linebot.models.responses.RichMenuResponse`) - :return: list[RichMenuResponse] instance - """ - response = self._get( - '/v2/bot/richmenu/list', - timeout=timeout - ) - - result = [] - for richmenu in response.json['richmenus']: - result.append(RichMenuResponse.new_from_json_dict(richmenu)) - - return result - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).set_default_rich_menu(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def set_default_rich_menu(self, rich_menu_id, timeout=None): - """Set the default rich menu. - - https://developers.line.biz/en/reference/messaging-api/#set-default-rich-menu - - :param str rich_menu_id: ID of an uploaded rich menu - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._post( - '/v2/bot/user/all/richmenu/{rich_menu_id}'.format( - rich_menu_id=rich_menu_id, - ), - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_default_rich_menu_id(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_default_rich_menu(self, timeout=None): - """Get the ID of the default rich menu set with the Messaging API. - - https://developers.line.biz/en/reference/messaging-api/#get-default-rich-menu-id - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - response = self._get( - '/v2/bot/user/all/richmenu', - timeout=timeout - ) - - return response.json.get('richMenuId') - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).cancel_default_rich_menu(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def cancel_default_rich_menu(self, timeout=None): - """Cancel the default rich menu set with the Messaging API. - - https://developers.line.biz/en/reference/messaging-api/#cancel-default-rich-menu - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._delete( - '/v2/bot/user/all/richmenu', - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_message_quota(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_message_quota(self, timeout=None): - """Call Get the target limit for additional messages. - - https://developers.line.biz/en/reference/messaging-api/#get-quota - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageQuotaResponse` - :return: MessageQuotaResponse instance - """ - response = self._get( - '/v2/bot/message/quota', - timeout=timeout - ) - - return MessageQuotaResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_message_quota_consumption(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_message_quota_consumption(self, timeout=None): - """Get number of messages sent this month. - - https://developers.line.biz/en/reference/messaging-api/#get-consumption - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageQuotaConsumptionResponse` - :return: MessageQuotaConsumptionResponse instance - """ - response = self._get( - '/v2/bot/message/quota/consumption', - timeout=timeout - ) - - return MessageQuotaConsumptionResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).issue_link_token(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def issue_link_token(self, user_id, timeout=None): - """Issues a link token used for the account link feature. - - https://developers.line.biz/en/reference/messaging-api/#issue-link-token - - :param str user_id: User ID for the LINE account to be linked - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.IssueLinkTokenResponse` - :return: IssueLinkTokenResponse instance - """ - response = self._post( - '/v2/bot/user/{user_id}/linkToken'.format( - user_id=user_id - ), - timeout=timeout - ) - - return IssueLinkTokenResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3.oauth import ChannelAccessToken' and 'ChannelAccessToken(...).issue_channel_token(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def issue_channel_token(self, client_id, client_secret, - grant_type='client_credentials', timeout=None): - """Issues a short-lived channel access token. - - https://developers.line.biz/en/reference/messaging-api/#issue-channel-access-token - - :param str client_id: Channel ID. - :param str client_secret: Channel secret. - :param str grant_type: `client_credentials` - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.IssueChannelTokenResponse` - :return: IssueChannelTokenResponse instance - """ - response = self._post( - '/v2/oauth/accessToken', - data={ - 'client_id': client_id, - 'client_secret': client_secret, - 'grant_type': grant_type, - }, - headers={'Content-Type': 'application/x-www-form-urlencoded'}, - timeout=timeout - ) - - return IssueChannelTokenResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3.oauth import ChannelAccessToken' and 'ChannelAccessToken(...).revoke_channel_token(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def revoke_channel_token(self, access_token, timeout=None): - """Revokes a channel access token. - - https://developers.line.biz/en/reference/messaging-api/#revoke-channel-access-token - - :param str access_token: Channel access token. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._post( - '/v2/oauth/revoke', - data={'access_token': access_token}, - headers={'Content-Type': 'application/x-www-form-urlencoded'}, - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_number_of_message_deliveries(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_insight_message_delivery(self, date, timeout=None): - """Get the number of messages sent on a specified day. - - https://developers.line.biz/en/reference/messaging-api/#get-number-of-delivery-messages - - :param str date: Date for which to retrieve number of sent messages. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.InsightMessageDeliveryResponse` - """ - response = self._get( - '/v2/bot/insight/message/delivery?date={date}'.format(date=date), - timeout=timeout - ) - - return InsightMessageDeliveryResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_insight_followers(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_insight_followers(self, date, timeout=None): - """Get the number of users who have added the bot on or before a specified date. - - https://developers.line.biz/en/reference/messaging-api/#get-number-of-followers - - :param str date: Date for which to retrieve the number of followers. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.InsightFollowersResponse` - """ - response = self._get( - '/v2/bot/insight/followers?date={date}'.format(date=date), - timeout=timeout - ) - - return InsightFollowersResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_friends_demographics(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_insight_demographic(self, timeout=None): - """Retrieve the demographic attributes for a bot's friends. - - https://developers.line.biz/en/reference/messaging-api/#get-demographic - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.InsightDemographicResponse` - """ - response = self._get( - '/v2/bot/insight/demographic', - timeout=timeout - ) - - return InsightDemographicResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_message_event(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_insight_message_event(self, request_id, timeout=None): - """Return statistics about how users interact with broadcast messages. - - https://developers.line.biz/en/reference/messaging-api/#get-message-event - - :param str request_id: Request ID of broadcast message. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.InsightMessageEventResponse` - """ - response = self._get( - '/v2/bot/insight/message/event?requestId={request_id}'.format(request_id=request_id), - timeout=timeout - ) - - return InsightMessageEventResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_bot_info(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_bot_info(self, timeout=None): - """Get a bot's basic information. - - https://developers.line.biz/en/reference/messaging-api/#get-bot-info - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.BotInfo` - """ - response = self._get( - '/v2/bot/info', - timeout=timeout - ) - - return BotInfo.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).create_audience_group(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def create_audience_group(self, audience_group_name, audiences=None, - is_ifa=False, timeout=None): - """Create an audience group. - - https://developers.line.biz/en/reference/messaging-api/#create-upload-audience-group - - :param str audience_group_name: The audience's name - :param list audiences: An array of user IDs or IFAs - :param bool is_ifa: true | false - :return: audience group id - """ - if audiences is None: - audiences = [] - - if audiences: - audiences = [Audience.new_from_json_dict(audience) for audience in audiences] - response = self._post( - '/v2/bot/audienceGroup/upload', - data=json.dumps({ - "description": audience_group_name, - "isIfaAudience": is_ifa, - "audiences": [audience.as_json_dict() for audience in audiences], - }), - timeout=timeout - ) - - return CreateAudienceGroup.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_audience_data(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_audience_group(self, audience_group_id, timeout=None): - """Get the object of audience group. - - https://developers.line.biz/en/reference/messaging-api/#get-audience-group - - :param str audience_group_id: The audience ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :return: AudienceGroup instance - """ - response = self._get( - '/v2/bot/audienceGroup/{audience_group_id}'.format( - audience_group_id=audience_group_id), - timeout=timeout - ) - - return AudienceGroup.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_audience_groups(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_audience_group_list(self, page=1, description=None, status=None, size=20, - include_external_public_group=None, create_route=None, - timeout=None): - """Get data for more than one audience. - - https://developers.line.biz/en/reference/messaging-api/#get-audience-groups - - :param int page: The page to return when getting (paginated) results. Must be 1 or higher - :param str description: The name of the audience(s) to return - :param str status: IN_PROGRESS | READY | FAILED | EXPIRED - :param int size: The number of audiences per page. Default: 20, Max: 40 - :param bool include_external_public_group: true | false - :param str create_route: How the audience was created. - :type create_route: OA_MANAGER | MESSAGING_API - :return: AudienceGroup instance - """ - params = {} - if page: - params["page"] = page - if description: - params["description"] = description - if status: - params["status"] = status - if size: - params["size"] = size - if include_external_public_group: - params["includesExternalPublicGroup"] = include_external_public_group - if create_route: - params["createRoute"] = create_route - response = self._get( - '/v2/bot/audienceGroup/list?', - params=params, - timeout=timeout - ) - result = [] - for audience_group in response.json.get('audienceGroups', []): - result.append(AudienceGroup.new_from_json_dict(audience_group)) - if response.json.get('hasNextPage', False): - result += self.get_audience_group_list(page + 1, description, status, size, - include_external_public_group, - create_route, timeout) - return result - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).delete_audience_group(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def delete_audience_group(self, audience_group_id, timeout=None): - """Delete an existing audience. - - https://developers.line.biz/en/reference/messaging-api/#delete-audience-group - - :param str audience_group_id: The audience ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._delete( - '/v2/bot/audienceGroup/{}'.format(audience_group_id), - timeout=timeout - ) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).update_audience_group_description(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def rename_audience_group(self, audience_group_id, description, timeout=None): - """Modify the name of an existing audience. - - https://developers.line.biz/en/reference/messaging-api/#set-description-audience-group - - :param str audience_group_id: The audience ID - :param str description: The new audience's name - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._put( - '/v2/bot/audienceGroup/{audience_group_id}/updateDescription'.format( - audience_group_id=audience_group_id), - data=json.dumps({ - "description": description, - }), - timeout=timeout - ) - - return '' - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).add_audience_to_audience_group(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def add_audiences_to_audience_group(self, audience_group_id, audiences, - upload_description=None, timeout=None): - """Add new user IDs or IFAs to an audience for uploading user IDs. - - https://developers.line.biz/en/reference/messaging-api/#update-upload-audience-group - - :param str audience_group_id: The audience ID - :param list audiences: An array of user IDs or IFAs - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :param bool is_ifa: If this is false (default), recipients are specified by user IDs. - If true, recipients must be specified by IFAs. - :param str upload_description: The description to register for the job - :type timeout: float | tuple(float, float) - """ - if audiences: - audiences = [Audience.new_from_json_dict(audience) for audience in audiences] - response = self._put( - '/v2/bot/audienceGroup/upload', - data=json.dumps({ - "audienceGroupId": audience_group_id, - "audiences": [audience.as_json_dict() for audience in audiences], - "uploadDescription": upload_description, - }), - timeout=timeout - ) - - return response.json - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_audience_group_authority_level(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_audience_group_authority_level(self, timeout=None): - """Get the authority level of the audience. - - https://developers.line.biz/en/reference/messaging-api/#get-authority-level - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :return: json - """ - response = self._get( - '/v2/bot/audienceGroup/authorityLevel', - timeout=timeout - ) - - return GetAuthorityLevel.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).update_audience_group_authority_level(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def change_audience_group_authority_level(self, authority_level='PUBLIC', timeout=None): - """Change the authority level of all audiences created in the same channel. - - https://developers.line.biz/en/reference/messaging-api/#change-authority-level - - :param str authority_level: PUBLIC | PRIVATE. - """ - self._put( - '/v2/bot/audienceGroup/authorityLevel', - data=json.dumps({ - "authorityLevel": authority_level, - }), - timeout=timeout - ) - - return '' - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).create_click_based_audience_group(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def create_click_audience_group(self, description, request_id, - click_url=None, timeout=None): - """Create an audience for click-based retargeting. - - https://developers.line.biz/en/reference/messaging-api/#create-click-audience-group - - :param str description: The audience's name. Audience names must be unique. - :param str request_id: The request ID of a message sent in the past 60 days. - :param str click_url: The URL clicked by the user. - If empty, users who clicked any URL in the message are added to the list of recipients. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :return: ClickAudienceGroup instance - """ - response = self._post( - '/v2/bot/audienceGroup/click', - data=json.dumps({ - "description": description, - "requestId": request_id, - "clickUrl": click_url, - }), - timeout=timeout - ) - - return ClickAudienceGroup.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).create_imp_based_audience_group(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def create_imp_audience_group(self, description, request_id, - timeout=None): - """Create an audience for impression-based retargeting. - - https://developers.line.biz/en/reference/messaging-api/#create-imp-audience-group - - :param str description: The audience's name. Audience names must be unique. - :param str request_id: The request ID of a message sent in the past 60 days. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :return: ImpAudienceGroup instance - """ - response = self._post( - '/v2/bot/audienceGroup/imp', - data=json.dumps({ - "description": description, - "requestId": request_id, - }), - timeout=timeout - ) - - return ImpAudienceGroup.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).set_webhook_endpoint(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def set_webhook_endpoint(self, webhook_endpoint, timeout=None): - """Set the webhook endpoint URL. - - https://developers.line.biz/en/reference/messaging-api/#set-webhook-endpoint-url - - :param str webhook_endpoint: A valid webhook URL to be set. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: dict - :return: Empty dict. - """ - data = { - 'endpoint': webhook_endpoint - } - - response = self._put( - '/v2/bot/channel/webhook/endpoint', - data=json.dumps(data), - timeout=timeout, - ) - - return response.json - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_webhook_endpoint(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_webhook_endpoint(self, timeout=None): - """Get information on a webhook endpoint. - - https://developers.line.biz/en/reference/messaging-api/#get-webhook-endpoint-information - - :rtype: :py:class:`linebot.models.responses.GetWebhookResponse` - :return: Webhook information, including `endpoint` for webhook - URL and `active` for webhook usage status. - """ - response = self._get( - '/v2/bot/channel/webhook/endpoint', - timeout=timeout, - ) - - return GetWebhookResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).test_webhook_endpoint(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def test_webhook_endpoint(self, webhook_endpoint=None, timeout=None): - """Checks if the configured webhook endpoint can receive a test webhook event. - - https://developers.line.biz/en/reference/messaging-api/#test-webhook-endpoint - - :param webhook_endpoint: (optional) Set this parameter to - specific the webhook endpoint of the webhook. Default is the webhook - endpoint that is already set to the channel. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.TestWebhookResponse` - """ - data = {} - - if webhook_endpoint is not None: - data['endpoint'] = webhook_endpoint - - response = self._post( - '/v2/bot/channel/webhook/test', - data=json.dumps(data), - timeout=timeout, - ) - - return TestWebhookResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_followers(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_followers_ids(self, limit=300, start=None, timeout=None): - """Get a list of users who added your LINE Official Account as a friend. - - https://developers.line.biz/en/reference/messaging-api/#get-follower-ids - - :param int limit: The maximum number of user IDs to retrieve in a single request. - The default value is 300. - :param str start: Get the next array of user IDs. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.UserIds` - """ - params = {'limit': limit} if start is None else {'limit': limit, 'start': start} - - response = self._get( - '/v2/bot/followers/ids', - params=params, - timeout=timeout - ) - - return UserIds.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3.oauth import ChannelAccessToken' and 'ChannelAccessToken(...).issue_channel_token_by_jwt(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def issue_channel_access_token_v2_1( - self, client_assertion, grant_type='client_credentials', - client_assertion_type='urn:ietf:params:oauth:client-assertion-type:jwt-bearer', - timeout=None): - """Issues a channel access token v2.1. - - https://developers.line.biz/en/reference/messaging-api/#issue-channel-access-token-v2-1 - - :param str client_assertion: Client assertion. - :param str grant_type: `client_credentials` - :param str client_assertion_type: `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.IssueChannelTokenResponseV2` - """ - response = self._post( - '/oauth2/v2.1/token', - data={ - 'grant_type': grant_type, - 'client_assertion_type': client_assertion_type, - 'client_assertion': client_assertion, - }, - headers={'Content-Type': 'application/x-www-form-urlencoded'}, - timeout=timeout - ) - - return IssueChannelTokenResponseV2.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3.oauth import ChannelAccessToken' and 'ChannelAccessToken(...).revoke_channel_token_by_jwt(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def revoke_channel_access_token_v2_1( - self, client_id, - client_secret, access_token, - timeout=None): - """Revokes a channel access token v2.1. - - https://developers.line.biz/en/reference/messaging-api/#revoke-channel-access-token-v2-1 - - :param str client_id: Client id. - :param str client_secret: Channel secret. - :param str access_token: Channel access token. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - """ - self._post( - '/oauth2/v2.1/revoke', - data={'client_id': client_id, - 'client_secret': client_secret, - 'access_token': access_token}, - timeout=timeout - ) - - def get_channel_access_tokens_v2_1( - self, client_assertion, - client_assertion_type='urn:ietf:params:oauth:client-assertion-type:jwt-bearer', - timeout=None): - """Get issued channel access tokens v2.1. - - https://developers.line.biz/en/reference/messaging-api/#get-issued-channel-access-tokens-v2-1 - - :param str client_assertion: Client assertion. - :param str client_assertion_type: `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.ChannelAccessTokens` - """ - response = self._get( - '/oauth2/v2.1/tokens', - params={'client_assertion': client_assertion, - 'client_assertion_type': client_assertion_type}, - timeout=timeout - ) - return ChannelAccessTokens.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3.oauth import ChannelAccessToken' and 'ChannelAccessToken(...).verify_channel_token_by_jwt(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def verify_channel_access_token_v2_1(self, access_token, timeout=None): - """Validate channel access token v2.1. - - https://developers.line.biz/en/reference/messaging-api/#verfiy-channel-access-token-v2-1 - - :param str access_token: Channel access token. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.VerifyChannelTokenResponseV2` - """ - response = self._get('/oauth2/v2.1/verify', - params={'access_token': access_token}, - timeout=timeout) - return VerifyChannelTokenResponseV2.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3.oauth import ChannelAccessToken' and 'ChannelAccessToken(...).gets_all_valid_channel_access_token_key_ids(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_channel_token_key_ids_v2_1( - self, client_assertion, - client_assertion_type='urn:ietf:params:oauth:client-assertion-type:jwt-bearer', - timeout=None): - """Get all valid channel access token key IDs v2.1. - - https://developers.line.biz/en/reference/messaging-api/#get-all-valid-channel-access-token-key-ids-v2-1 - - :param str client_assertion: Client assertion. - :param str client_assertion_type: `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.VerifyChannelTokenResponseV2` - """ - response = self._get('/oauth2/v2.1/tokens/kid', - params={"client_assertion": client_assertion, - "client_assertion_type": client_assertion_type}, - timeout=timeout) - return ValidAccessTokenKeyIDsResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_statistics_per_unit(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_statistics_per_unit(self, custom_aggregation_unit, from_date, to_date, timeout=None): - """Return statistics about how users interact with push and multicast messages. - - https://developers.line.biz/en/reference/partner-docs/#get-statistics-per-unit - - :param str custom_aggregation_unit: Name of aggregation unit specified when sending - the message like `push_message(...)` and `multicast(...)`. - :param str from_date: Start date of aggregation period. - The format is `yyyyMMdd` (Timezone is UTC+9). - :param str to_date: End date of aggregation period. - The end date can be specified for up to 30 days later. - The format is `yyyyMMdd` (Timezone is UTC+9). - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class: - `linebot.models.responses.InsightMessageEventOfCustomAggregationUnitResponse` - """ - response = self._get( - '/v2/bot/insight/message/event/aggregation?' - 'customAggregationUnit={custom_aggregation_unit}&from={from_date}&to={to_date}'.format( - custom_aggregation_unit=custom_aggregation_unit, - from_date=from_date, to_date=to_date), - timeout=timeout - ) - - return InsightMessageEventOfCustomAggregationUnitResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_aggregation_unit_usage(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_number_of_units_used_this_month(self, timeout=None): - """Return the number of aggregation units used this month. - - https://developers.line.biz/en/reference/partner-docs/#get-number-of-units-used-this-month - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class: `linebot.models.responses.AggregationInfoResponse` - """ - response = self._get('/v2/bot/message/aggregation/info', timeout=timeout) - return AggregationInfoResponse.new_from_json_dict(response.json) - - @deprecated(reason="Use 'from linebot.v3 import LineBotClient' and 'LineBotClient(...).get_aggregation_unit_name_list(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 - def get_name_list_of_units_used_this_month(self, limit=100, start=None, timeout=None): - """Return the name list of units used this month for statistics aggregation. - - :param int limit: Maximum number of aggregation units you can get per request. - If you don't specify a value, or if you specify a value greater than or equal to 100, - the maximum is 100. - :param str start: Get the next array of name list of units - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class: `linebot.models.responses.AggregationNameListResponse` - """ - params = {'limit': limit} if start is None else {'limit': limit, 'start': start} - - response = self._get( - '/v2/bot/message/aggregation/list', - params=params, - timeout=timeout - ) - - return AggregationNameListResponse.new_from_json_dict(response.json) - - def _get(self, path, endpoint=None, params=None, headers=None, stream=False, timeout=None): - url = (endpoint or self.endpoint) + path - - if headers is None: - headers = {} - headers.update(self.headers) - - response = self.http_client.get( - url, headers=headers, params=params, stream=stream, timeout=timeout - ) - - self.__check_error(response) - return response - - def _post(self, path, endpoint=None, data=None, headers=None, timeout=None): - url = (endpoint or self.endpoint) + path - - if headers is None: - headers = {'Content-Type': 'application/json'} - headers.update(self.headers) - - response = self.http_client.post( - url, headers=headers, data=data, timeout=timeout - ) - - self.__check_error(response) - return response - - def _delete(self, path, endpoint=None, data=None, headers=None, timeout=None): - url = (endpoint or self.endpoint) + path - - if headers is None: - headers = {} - headers.update(self.headers) - - response = self.http_client.delete( - url, headers=headers, data=data, timeout=timeout - ) - - self.__check_error(response) - return response - - def _put(self, path, endpoint=None, data=None, headers=None, timeout=None): - url = (endpoint or self.endpoint) + path - - if headers is None: - headers = {'Content-Type': 'application/json'} - headers.update(self.headers) - - response = self.http_client.put( - url, headers=headers, data=data, timeout=timeout - ) - - self.__check_error(response) - return response - - @staticmethod - def __check_error(response): - if 200 <= response.status_code < 300: - pass - else: - raise LineBotApiError( - status_code=response.status_code, - headers=dict(response.headers.items()), - request_id=response.headers.get('X-Line-Request-Id'), - accepted_request_id=response.headers.get('X-Line-Accepted-Request-Id'), - error=Error.new_from_json_dict(response.json) - ) diff --git a/linebot/async_api.py b/linebot/async_api.py deleted file mode 100644 index c71aaa833..000000000 --- a/linebot/async_api.py +++ /dev/null @@ -1,2569 +0,0 @@ -# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -# -# *** DO NOT EDIT THIS FILE *** -# -# 1) Modify linebot/api.py -# 2) Run `python setup.py codegen` -# -# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.async_api module.""" - -import json - -from .__about__ import __version__ -from .exceptions import LineBotApiError - -from .models import ( - Error, - Profile, - MemberIds, - Content, - RichMenuResponse, - MessageQuotaResponse, - MessageQuotaConsumptionResponse, - IssueLinkTokenResponse, - IssueChannelTokenResponse, - MessageDeliveryBroadcastResponse, - MessageDeliveryMulticastResponse, - MessageDeliveryPushResponse, - MessageDeliveryReplyResponse, - InsightMessageDeliveryResponse, - InsightFollowersResponse, - InsightDemographicResponse, - InsightMessageEventResponse, - BroadcastResponse, - NarrowcastResponse, - MessageProgressNarrowcastResponse, - BotInfo, - GetWebhookResponse, - TestWebhookResponse, - AudienceGroup, - ClickAudienceGroup, - ImpAudienceGroup, - GetAuthorityLevel, - Audience, - CreateAudienceGroup, -) -from .models.responses import ( - Group, - UserIds, - RichMenuAliasResponse, - RichMenuAliasListResponse, - ChannelAccessTokens, - IssueChannelTokenResponseV2, - VerifyChannelTokenResponseV2, - ValidAccessTokenKeyIDsResponse, - InsightMessageEventOfCustomAggregationUnitResponse, - AggregationInfoResponse, - AggregationNameListResponse, - ValidateBroadcastMessageObjectsResponse, - ValidateMulticastMessageObjectsResponse, - ValidateNarrowcastMessageObjectsResponse, - ValidatePushMessageObjectsResponse, - ValidateReplyMessageObjectsResponse, -) -from .deprecations import LineBotSdkDeprecatedIn30 - -from deprecated import deprecated - - -@deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient'. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, -) # noqa: E501 -class AsyncLineBotApi(object): - """LineBotApi provides interface for LINE messaging API.""" - - DEFAULT_API_ENDPOINT = "https://api.line.me" - DEFAULT_API_DATA_ENDPOINT = "https://api-data.line.me" - - def __init__( - self, - channel_access_token, - async_http_client, - endpoint=DEFAULT_API_ENDPOINT, - data_endpoint=DEFAULT_API_DATA_ENDPOINT, - ): - """__init__ method. - - :param str channel_access_token: Your channel access token - :param str endpoint: (optional) Default is https://api.line.me - :param str data_endpoint: (optional) Default is https://api-data.line.me - - """ - self.data_endpoint = data_endpoint - self.endpoint = endpoint - self.headers = { - "Authorization": "Bearer " + channel_access_token, - "User-Agent": "line-bot-sdk-python-async/" + __version__, - } - - self.async_http_client = async_http_client - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).reply_message(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def reply_message( - self, reply_token, messages, notification_disabled=False, timeout=None - ): - """Call reply message API. - - https://developers.line.biz/en/reference/messaging-api/#send-reply-message - - Respond to events from users, groups, and rooms. - - Webhooks are used to notify you when an event occurs. - For events that you can respond to, a replyToken is issued for replying to messages. - - Because the replyToken becomes invalid after a certain period of time, - responses should be sent as soon as a message is received. - - Reply tokens can only be used once. - - :param str reply_token: replyToken received via webhook - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param bool notification_disabled: (optional) True to disable push notification - when the message is sent. The default value is False. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - data = { - "replyToken": reply_token, - "messages": [message.as_json_dict() for message in messages], - "notificationDisabled": notification_disabled, - } - - await self._post( - "/v2/bot/message/reply", data=json.dumps(data), timeout=timeout - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).push_message(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def push_message( - self, - to, - messages, - retry_key=None, - notification_disabled=False, - custom_aggregation_units=None, - timeout=None, - ): - """Call push message API. - - https://developers.line.biz/en/reference/messaging-api/#send-push-message - - Send messages to users, groups, and rooms at any time. - - :param str to: ID of the receiver - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param retry_key: (optional) Arbitrarily generated UUID in hexadecimal notation. - :param bool notification_disabled: (optional) True to disable push notification - when the message is sent. The default value is False. - :param custom_aggregation_units: (optional) Name of aggregation unit. Case-sensitive. - Max unit: 1 - Max aggregation unit name length: 30 characters - Supported character types: Half-width alphanumeric characters and underscore - :type custom_aggregation_units: str | list[str] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - if retry_key: - self.headers["X-Line-Retry-Key"] = retry_key - - data = { - "to": to, - "messages": [message.as_json_dict() for message in messages], - "notificationDisabled": notification_disabled, - } - - if custom_aggregation_units is not None: - if not isinstance(custom_aggregation_units, (list, tuple)): - custom_aggregation_units = [custom_aggregation_units] - data["customAggregationUnits"] = custom_aggregation_units - - await self._post("/v2/bot/message/push", data=json.dumps(data), timeout=timeout) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).multicast(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def multicast( - self, - to, - messages, - retry_key=None, - notification_disabled=False, - custom_aggregation_units=None, - timeout=None, - ): - """Call multicast API. - - https://developers.line.biz/en/reference/messaging-api/#send-multicast-message - - Sends push messages to multiple users at any time. - Messages cannot be sent to groups or rooms. - - :param to: IDs of the receivers - Max: 500 users - :type to: list[str] - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param retry_key: (optional) Arbitrarily generated UUID in hexadecimal notation. - :param bool notification_disabled: (optional) True to disable push notification - when the message is sent. The default value is False. - :param custom_aggregation_units: (optional) Name of aggregation unit. Case-sensitive. - Max unit: 1 - Max aggregation unit name length: 30 characters - Supported character types: Half-width alphanumeric characters and underscore - :type custom_aggregation_units: str | list[str] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - if retry_key: - self.headers["X-Line-Retry-Key"] = retry_key - - data = { - "to": to, - "messages": [message.as_json_dict() for message in messages], - "notificationDisabled": notification_disabled, - } - - if custom_aggregation_units is not None: - if not isinstance(custom_aggregation_units, (list, tuple)): - custom_aggregation_units = [custom_aggregation_units] - data["customAggregationUnits"] = custom_aggregation_units - - await self._post( - "/v2/bot/message/multicast", data=json.dumps(data), timeout=timeout - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).broadcast(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def broadcast( - self, messages, retry_key=None, notification_disabled=False, timeout=None - ): - """Call broadcast API. - - https://developers.line.biz/en/reference/messaging-api/#send-broadcast-message - - Sends push messages to multiple users at any time. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param retry_key: (optional) Arbitrarily generated UUID in hexadecimal notation. - :param bool notification_disabled: (optional) True to disable push notification - when the message is sent. The default value is False. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.BroadcastResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - if retry_key: - self.headers["X-Line-Retry-Key"] = retry_key - - data = { - "messages": [message.as_json_dict() for message in messages], - "notificationDisabled": notification_disabled, - } - - response = await self._post( - "/v2/bot/message/broadcast", data=json.dumps(data), timeout=timeout - ) - - return BroadcastResponse(request_id=response.headers.get("X-Line-Request-Id")) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).narrowcast(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def narrowcast( - self, - messages, - retry_key=None, - recipient=None, - filter=None, - limit=None, - notification_disabled=False, - timeout=None, - ): - """Call narrowcast API. - - https://developers.line.biz/en/reference/messaging-api/#send-narrowcast-message - - Sends push messages to multiple users at any time. - Messages cannot be sent to groups or rooms. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param retry_key: (optional) Arbitrarily generated UUID in hexadecimal notation. - :param recipient: audience object of recipient - :type recipient: T <= :py:class:`linebot.models.recipient.AudienceRecipient` - :param filter: demographic filter of recipient - :type filter: T <= :py:class:`linebot.models.filter.DemographicFilter` - :param limit: limit on this narrowcast - :type limit: T <= :py:class:`linebot.models.limit.Limit` - :param bool notification_disabled: (optional) True to disable push notification - when the message is sent. The default value is False. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.NarrowcastResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - if retry_key: - self.headers["X-Line-Retry-Key"] = retry_key - - data = { - "messages": [message.as_json_dict() for message in messages], - "recipient": recipient.as_json_dict(), - "filter": filter.as_json_dict(), - "limit": limit.as_json_dict(), - "notificationDisabled": notification_disabled, - } - - response = await self._post( - "/v2/bot/message/narrowcast", data=json.dumps(data), timeout=timeout - ) - - return NarrowcastResponse(request_id=response.headers.get("X-Line-Request-Id")) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_narrowcast_progress(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_progress_status_narrowcast(self, request_id, timeout=None): - """Get progress status of narrowcast messages sent. - - https://developers.line.biz/en/reference/messaging-api/#get-narrowcast-progress-status - - Gets the number of messages sent with the /bot/message/progress/narrowcast endpoint. - - :param str request_id: request ID of narrowcast. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageDeliveryBroadcastResponse` - """ - response = await self._get( - "/v2/bot/message/progress/narrowcast?requestId={request_id}".format( - request_id=request_id - ), - timeout=timeout, - ) - - return MessageProgressNarrowcastResponse.new_from_json_dict( - (await response.json) - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).validate_reply(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def validate_reply_message_objects(self, messages, timeout=None): - """Call validate reply message objects API. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-reply-message - - You can validate that an array of message objects is valid as a value - for the messages property of the request body for the send reply message endpoint. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.ValidateReplyMessageObjectsResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - data = { - "messages": [message.as_json_dict() for message in messages], - } - - response = await self._post( - "/v2/bot/message/validate/reply", data=json.dumps(data), timeout=timeout - ) - - return ValidateReplyMessageObjectsResponse( - request_id=response.headers.get("X-Line-Request-Id") - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).validate_push(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def validate_push_message_objects(self, messages, timeout=None): - """Call validate push message objects API. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-push-message - - You can validate that an array of message objects is valid as a value - for the messages property of the request body for the send push message endpoint. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.ValidatePushMessageObjectsResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - data = { - "messages": [message.as_json_dict() for message in messages], - } - - response = await self._post( - "/v2/bot/message/validate/push", data=json.dumps(data), timeout=timeout - ) - - return ValidatePushMessageObjectsResponse( - request_id=response.headers.get("X-Line-Request-Id") - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).validate_multicast(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def validate_multicast_message_objects(self, messages, timeout=None): - """Call validate multicast message objects API. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-multicast-message - - You can validate that an array of message objects is valid as a value - for the messages property of the request body for the send multicast message endpoint. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.ValidateMulticastMessageObjectsResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - data = { - "messages": [message.as_json_dict() for message in messages], - } - - response = await self._post( - "/v2/bot/message/validate/multicast", data=json.dumps(data), timeout=timeout - ) - - return ValidateMulticastMessageObjectsResponse( - request_id=response.headers.get("X-Line-Request-Id") - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).validate_broadcast(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def validate_broadcast_message_objects(self, messages, timeout=None): - """Call validate broadcast message objects API. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-broadcast-message - - You can validate that an array of message objects is valid as a value - for the messages property of the request body for the send broadcast message endpoint. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.ValidateBroadcastMessageObjectsResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - data = { - "messages": [message.as_json_dict() for message in messages], - } - - response = await self._post( - "/v2/bot/message/validate/broadcast", data=json.dumps(data), timeout=timeout - ) - - return ValidateBroadcastMessageObjectsResponse( - request_id=response.headers.get("X-Line-Request-Id") - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).validate_narrowcast(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def validate_narrowcast_message_objects(self, messages, timeout=None): - """Call validate narrowcast message objects API. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-narrowcast-message - - You can validate that an array of message objects is valid as a value - for the messages property of the request body for the send narrowcast message endpoint. - - :param messages: Messages. - Max: 5 - :type messages: T <= :py:class:`linebot.models.send_messages.SendMessage` | - list[T <= :py:class:`linebot.models.send_messages.SendMessage`] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.ValidateNarrowcastMessageObjectsResponse` - """ - if not isinstance(messages, (list, tuple)): - messages = [messages] - - data = { - "messages": [message.as_json_dict() for message in messages], - } - - response = await self._post( - "/v2/bot/message/validate/narrowcast", - data=json.dumps(data), - timeout=timeout, - ) - - return ValidateNarrowcastMessageObjectsResponse( - request_id=response.headers.get("X-Line-Request-Id") - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_number_of_sent_broadcast_messages(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_message_delivery_broadcast(self, date, timeout=None): - """Get number of sent broadcast messages. - - https://developers.line.biz/en/reference/messaging-api/#get-number-of-broadcast-messages - - Gets the number of messages sent with the /bot/message/broadcast endpoint. - - :param str date: Date the messages were sent. The format is `yyyyMMdd` (Timezone is UTC+9). - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageDeliveryBroadcastResponse` - """ - response = await self._get( - "/v2/bot/message/delivery/broadcast?date={date}".format(date=date), - timeout=timeout, - ) - - return MessageDeliveryBroadcastResponse.new_from_json_dict( - (await response.json) - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_number_of_sent_reply_messages(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_message_delivery_reply(self, date, timeout=None): - """Get number of sent reply messages. - - https://developers.line.biz/en/reference/messaging-api/#get-number-of-reply-messages - - Gets the number of messages sent with the /bot/message/reply endpoint. - - :param str date: Date the messages were sent. The format is `yyyyMMdd` (Timezone is UTC+9). - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageDeliveryReplyResponse` - """ - response = await self._get( - "/v2/bot/message/delivery/reply?date={date}".format(date=date), - timeout=timeout, - ) - - return MessageDeliveryReplyResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_number_of_sent_push_messages(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_message_delivery_push(self, date, timeout=None): - """Get number of sent push messages. - - https://developers.line.biz/en/reference/messaging-api/#get-number-of-push-messages - - Gets the number of messages sent with the /bot/message/push endpoint. - - :param str date: Date the messages were sent. The format is `yyyyMMdd` (Timezone is UTC+9). - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageDeliveryPushResponse` - """ - response = await self._get( - "/v2/bot/message/delivery/push?date={date}".format(date=date), - timeout=timeout, - ) - - return MessageDeliveryPushResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_number_of_sent_multicast_messages(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_message_delivery_multicast(self, date, timeout=None): - """Get number of sent multicast messages. - - https://developers.line.biz/en/reference/messaging-api/#get-number-of-multicast-messages - - Gets the number of messages sent with the /bot/message/multicast endpoint. - - :param str date: Date the messages were sent. The format is `yyyyMMdd` (Timezone is UTC+9). - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageDeliveryMulticastResponse` - """ - response = await self._get( - "/v2/bot/message/delivery/multicast?date={date}".format(date=date), - timeout=timeout, - ) - - return MessageDeliveryMulticastResponse.new_from_json_dict( - (await response.json) - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_profile(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_profile(self, user_id, timeout=None): - """Call get profile API. - - https://developers.line.biz/en/reference/messaging-api/#get-profile - - Get user profile information. - - :param str user_id: User ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Profile` - :return: Profile instance - """ - response = await self._get( - "/v2/bot/profile/{user_id}".format(user_id=user_id), timeout=timeout - ) - - return Profile.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_group_summary(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_group_summary(self, group_id, timeout=None): - """Call get group summary API. - - https://developers.line.biz/en/reference/messaging-api/#get-group-summary - - Gets the group ID, group name, and group icon URL of a group - where the LINE Official Account is a member. - - :param str group_id: Group ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Group` - :return: Profile instance - """ - response = await self._get( - "/v2/bot/group/{group_id}/summary".format(group_id=group_id), - timeout=timeout, - ) - - return Group.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_group_member_count(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_group_members_count(self, group_id, timeout=None): - """Call get members in group count API. - - https://developers.line.biz/en/reference/messaging-api/#get-members-group-count - - Gets the count of members in a group. - - :param str group_id: Group ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Group` - :return: Profile instance - """ - response = await self._get( - "/v2/bot/group/{group_id}/members/count".format(group_id=group_id), - timeout=timeout, - ) - - return (await response.json).get("count") - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_room_member_count(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_room_members_count(self, room_id, timeout=None): - """Call get members in room count API. - - https://developers.line.biz/en/reference/messaging-api/#get-members-room-count - - Gets the count of members in a room. - - :param str room_id: Room ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Group` - :return: Profile instance - """ - response = await self._get( - "/v2/bot/room/{room_id}/members/count".format(room_id=room_id), - timeout=timeout, - ) - - return (await response.json).get("count") - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_group_member_profile(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_group_member_profile(self, group_id, user_id, timeout=None): - """Call get group member profile API. - - https://developers.line.biz/en/reference/messaging-api/#get-group-member-profile - - Gets the user profile of a member of a group that - the bot is in. This can be the user ID of a user who has - not added the bot as a friend or has blocked the bot. - - :param str group_id: Group ID - :param str user_id: User ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Profile` - :return: Profile instance - """ - response = await self._get( - "/v2/bot/group/{group_id}/member/{user_id}".format( - group_id=group_id, user_id=user_id - ), - timeout=timeout, - ) - - return Profile.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_room_member_profile(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_room_member_profile(self, room_id, user_id, timeout=None): - """Call get room member profile API. - - https://developers.line.biz/en/reference/messaging-api/#get-room-member-profile - - Gets the user profile of a member of a room that - the bot is in. This can be the user ID of a user who has - not added the bot as a friend or has blocked the bot. - - :param str room_id: Room ID - :param str user_id: User ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Profile` - :return: Profile instance - """ - response = await self._get( - "/v2/bot/room/{room_id}/member/{user_id}".format( - room_id=room_id, user_id=user_id - ), - timeout=timeout, - ) - - return Profile.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_group_members_ids(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_group_member_ids(self, group_id, start=None, timeout=None): - """Call get group member IDs API. - - https://developers.line.biz/en/reference/messaging-api/#get-group-member-ids - - Gets the user IDs of the members of a group that the bot is in. - This includes the user IDs of users who have not added the bot as a friend - or has blocked the bot. - - :param str group_id: Group ID - :param str start: continuationToken - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MemberIds` - :return: MemberIds instance - """ - params = None if start is None else {"start": start} - - response = await self._get( - "/v2/bot/group/{group_id}/members/ids".format(group_id=group_id), - params=params, - timeout=timeout, - ) - - return MemberIds.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_room_members_ids(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_room_member_ids(self, room_id, start=None, timeout=None): - """Call get room member IDs API. - - https://developers.line.biz/en/reference/messaging-api/#get-room-member-ids - - Gets the user IDs of the members of a group that the bot is in. - This includes the user IDs of users who have not added the bot as a friend - or has blocked the bot. - - :param str room_id: Room ID - :param str start: continuationToken - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MemberIds` - :return: MemberIds instance - """ - params = None if start is None else {"start": start} - - response = await self._get( - "/v2/bot/room/{room_id}/members/ids".format(room_id=room_id), - params=params, - timeout=timeout, - ) - - return MemberIds.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_message_content(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_message_content(self, message_id, timeout=None): - """Call get content API. - - https://developers.line.biz/en/reference/messaging-api/#get-content - - Retrieve image, video, and audio data sent by users. - - :param str message_id: Message ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Content` - :return: Content instance - """ - response = await self._get( - "/v2/bot/message/{message_id}/content".format(message_id=message_id), - endpoint=self.data_endpoint, - timeout=timeout, - ) - - return Content(response) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).leave_group(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def leave_group(self, group_id, timeout=None): - """Call leave group API. - - https://developers.line.biz/en/reference/messaging-api/#leave-group - - Leave a group. - - :param str group_id: Group ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._post( - "/v2/bot/group/{group_id}/leave".format(group_id=group_id), timeout=timeout - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).leave_room(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def leave_room(self, room_id, timeout=None): - """Call leave room API. - - https://developers.line.biz/en/reference/messaging-api/#leave-room - - Leave a room. - - :param str room_id: Room ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._post( - "/v2/bot/room/{room_id}/leave".format(room_id=room_id), timeout=timeout - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_rich_menu(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_rich_menu(self, rich_menu_id, timeout=None): - """Call get rich menu API. - - https://developers.line.biz/en/reference/messaging-api/#get-rich-menu - - :param str rich_menu_id: ID of the rich menu - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.RichMenuResponse` - :return: RichMenuResponse instance - """ - response = await self._get( - "/v2/bot/richmenu/{rich_menu_id}".format(rich_menu_id=rich_menu_id), - timeout=timeout, - ) - - return RichMenuResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_rich_menu_alias(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_rich_menu_alias(self, rich_menu_alias_id=None, timeout=None): - """Call get rich menu alias API. - - https://developers.line.biz/en/reference/messaging-api/#get-rich-menu-alias-by-id - - :param str rich_menu_alias_id: ID of an uploaded rich menu alias. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.RichMenuAliasResponse` - :return: RichMenuAliasResponse instance - """ - response = await self._get( - "/v2/bot/richmenu/alias/{rich_menu_id}".format( - rich_menu_id=rich_menu_alias_id - ), - timeout=timeout, - ) - return RichMenuAliasResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_rich_menu_alias_list(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_rich_menu_alias_list(self, timeout=None): - """Call get rich menu alias list API. - - https://developers.line.biz/en/reference/messaging-api/#update-rich-menu-alias - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.RichMenuAliasListResponse` - :return: RichMenuAliasListResponse instance - """ - response = await self._get("/v2/bot/richmenu/alias/list", timeout=timeout) - return RichMenuAliasListResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).validate_rich_menu_object(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def validate_rich_menu_object(self, rich_menu, timeout=None): - """Call validate rich menu object API. - - https://developers.line.biz/ja/reference/messaging-api/#validate-rich-menu-object - - :param rich_menu: Inquired to validate a rich menu object. - :type rich_menu: T <= :py:class:`linebot.models.rich_menu.RichMenu` - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._post( - "/v2/bot/richmenu/validate", - data=rich_menu.as_json_string(), - timeout=timeout, - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).create_rich_menu(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def create_rich_menu(self, rich_menu, timeout=None): - """Call create rich menu API. - - https://developers.line.biz/en/reference/messaging-api/#create-rich-menu - - :param rich_menu: Inquired to create a rich menu object. - :type rich_menu: T <= :py:class:`linebot.models.rich_menu.RichMenu` - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: str - :return: rich menu id - """ - response = await self._post( - "/v2/bot/richmenu", data=rich_menu.as_json_string(), timeout=timeout - ) - - return (await response.json).get("richMenuId") - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).create_rich_menu_alias(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def create_rich_menu_alias(self, rich_menu_alias, timeout=None): - """Call create rich menu alias API. - - https://developers.line.biz/en/reference/messaging-api/#create-rich-menu-alias - - :param rich_menu_alias: Inquired to create a rich menu alias object. - :type rich_menu_alias: T <= :py:class:`linebot.models.rich_menu.RichMenuAlias` - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: str - :return: rich menu id - """ - await self._post( - "/v2/bot/richmenu/alias", - data=rich_menu_alias.as_json_string(), - timeout=timeout, - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).update_rich_menu_alias(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def update_rich_menu_alias( - self, rich_menu_alias_id, rich_menu_alias, timeout=None - ): - """Call update rich menu alias API. - - https://developers.line.biz/en/reference/messaging-api/#update-rich-menu-alias - - :param str rich_menu_alias_id: ID of an uploaded rich menu alias. - :param rich_menu_alias: Inquired to create a rich menu alias object. - :type rich_menu_alias: T <= :py:class:`linebot.models.rich_menu.RichMenuAlias` - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: str - :return: rich menu id - """ - await self._post( - "/v2/bot/richmenu/alias/{rich_menu_id}".format( - rich_menu_id=rich_menu_alias_id - ), - data=rich_menu_alias.as_json_string(), - timeout=timeout, - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).delete_rich_menu(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def delete_rich_menu(self, rich_menu_id, timeout=None): - """Call delete rich menu API. - - https://developers.line.biz/en/reference/messaging-api/#delete-rich-menu - - :param str rich_menu_id: ID of an uploaded rich menu - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._delete( - "/v2/bot/richmenu/{rich_menu_id}".format(rich_menu_id=rich_menu_id), - timeout=timeout, - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).delete_rich_menu_alias(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def delete_rich_menu_alias(self, rich_menu_alias_id, timeout=None): - """Call delete rich menu alias API. - - https://developers.line.biz/en/reference/messaging-api/#delete-rich-menu-alias - - :param str rich_menu_alias_id: ID of an uploaded rich menu alias. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._delete( - "/v2/bot/richmenu/alias/{rich_menu_alias_id}".format( - rich_menu_alias_id=rich_menu_alias_id - ), - timeout=timeout, - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_rich_menu_id_of_user(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_rich_menu_id_of_user(self, user_id, timeout=None): - """Call get rich menu ID of user API. - - https://developers.line.biz/en/reference/messaging-api/#get-rich-menu-id-of-user - - :param str user_id: IDs of the user - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: str - :return: rich menu id - """ - response = await self._get( - "/v2/bot/user/{user_id}/richmenu".format(user_id=user_id), timeout=timeout - ) - - return (await response.json).get("richMenuId") - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).link_rich_menu_id_to_user(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def link_rich_menu_to_user(self, user_id, rich_menu_id, timeout=None): - """Call link rich menu to user API. - - https://developers.line.biz/en/reference/messaging-api/#link-rich-menu-to-user - - :param str user_id: ID of the user - :param str rich_menu_id: ID of an uploaded rich menu - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._post( - "/v2/bot/user/{user_id}/richmenu/{rich_menu_id}".format( - user_id=user_id, rich_menu_id=rich_menu_id - ), - timeout=timeout, - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).link_rich_menu_id_to_users(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def link_rich_menu_to_users(self, user_ids, rich_menu_id, timeout=None): - """Links a rich menu to multiple users. - - https://developers.line.biz/en/reference/messaging-api/#link-rich-menu-to-users - - :param user_ids: user IDs - Max: 150 users - :type user_ids: list[str] - :param str rich_menu_id: ID of an uploaded rich menu - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._post( - "/v2/bot/richmenu/bulk/link", - data=json.dumps( - { - "userIds": user_ids, - "richMenuId": rich_menu_id, - } - ), - timeout=timeout, - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).unlink_rich_menu_id_from_user(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def unlink_rich_menu_from_user(self, user_id, timeout=None): - """Call unlink rich menu from user API. - - https://developers.line.biz/en/reference/messaging-api#unlink-rich-menu-from-user - - :param str user_id: ID of the user - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._delete( - "/v2/bot/user/{user_id}/richmenu".format(user_id=user_id), timeout=timeout - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).unlink_rich_menu_id_from_users(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def unlink_rich_menu_from_users(self, user_ids, timeout=None): - """Unlinks rich menus from multiple users. - - https://developers.line.biz/en/reference/messaging-api/#unlink-rich-menu-from-users - - :param user_ids: user IDs - Max: 150 users - :type user_ids: list[str] - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._post( - "/v2/bot/richmenu/bulk/unlink", - data=json.dumps( - { - "userIds": user_ids, - } - ), - timeout=timeout, - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_rich_menu_image(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_rich_menu_image(self, rich_menu_id, timeout=None): - """Call download rich menu image API. - - https://developers.line.biz/en/reference/messaging-api#download-rich-menu-image - - :param str rich_menu_id: ID of the rich menu with the image to be downloaded - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.Content` - :return: Content instance - """ - response = await self._get( - "/v2/bot/richmenu/{rich_menu_id}/content".format(rich_menu_id=rich_menu_id), - endpoint=self.data_endpoint, - timeout=timeout, - ) - - return Content(response) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).set_rich_menu_image(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def set_rich_menu_image( - self, rich_menu_id, content_type, content, timeout=None - ): - """Call upload rich menu image API. - - https://developers.line.me/en/docs/messaging-api/reference/#upload-rich-menu-image - - Uploads and attaches an image to a rich menu. - - :param str rich_menu_id: IDs of the richmenu - :param str content_type: image/jpeg or image/png - :param content: image content as bytes, or file-like object - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._post( - "/v2/bot/richmenu/{rich_menu_id}/content".format(rich_menu_id=rich_menu_id), - endpoint=self.data_endpoint, - data=content, - headers={"Content-Type": content_type}, - timeout=timeout, - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_rich_menu_list(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_rich_menu_list(self, timeout=None): - """Call get rich menu list API. - - https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu-list - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: list(T <= :py:class:`linebot.models.responses.RichMenuResponse`) - :return: list[RichMenuResponse] instance - """ - response = await self._get("/v2/bot/richmenu/list", timeout=timeout) - - result = [] - for richmenu in (await response.json)["richmenus"]: - result.append(RichMenuResponse.new_from_json_dict(richmenu)) - - return result - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).set_default_rich_menu(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def set_default_rich_menu(self, rich_menu_id, timeout=None): - """Set the default rich menu. - - https://developers.line.biz/en/reference/messaging-api/#set-default-rich-menu - - :param str rich_menu_id: ID of an uploaded rich menu - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._post( - "/v2/bot/user/all/richmenu/{rich_menu_id}".format( - rich_menu_id=rich_menu_id, - ), - timeout=timeout, - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_default_rich_menu_id(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_default_rich_menu(self, timeout=None): - """Get the ID of the default rich menu set with the Messaging API. - - https://developers.line.biz/en/reference/messaging-api/#get-default-rich-menu-id - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - response = await self._get("/v2/bot/user/all/richmenu", timeout=timeout) - - return (await response.json).get("richMenuId") - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).cancel_default_rich_menu(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def cancel_default_rich_menu(self, timeout=None): - """Cancel the default rich menu set with the Messaging API. - - https://developers.line.biz/en/reference/messaging-api/#cancel-default-rich-menu - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._delete("/v2/bot/user/all/richmenu", timeout=timeout) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_message_quota(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_message_quota(self, timeout=None): - """Call Get the target limit for additional messages. - - https://developers.line.biz/en/reference/messaging-api/#get-quota - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageQuotaResponse` - :return: MessageQuotaResponse instance - """ - response = await self._get("/v2/bot/message/quota", timeout=timeout) - - return MessageQuotaResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_message_quota_consumption(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_message_quota_consumption(self, timeout=None): - """Get number of messages sent this month. - - https://developers.line.biz/en/reference/messaging-api/#get-consumption - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.MessageQuotaConsumptionResponse` - :return: MessageQuotaConsumptionResponse instance - """ - response = await self._get("/v2/bot/message/quota/consumption", timeout=timeout) - - return MessageQuotaConsumptionResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).issue_link_token(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def issue_link_token(self, user_id, timeout=None): - """Issues a link token used for the account link feature. - - https://developers.line.biz/en/reference/messaging-api/#issue-link-token - - :param str user_id: User ID for the LINE account to be linked - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.IssueLinkTokenResponse` - :return: IssueLinkTokenResponse instance - """ - response = await self._post( - "/v2/bot/user/{user_id}/linkToken".format(user_id=user_id), timeout=timeout - ) - - return IssueLinkTokenResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3.oauth import AsyncChannelAccessToken' and 'AsyncChannelAccessToken(...).issue_channel_token(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def issue_channel_token( - self, client_id, client_secret, grant_type="client_credentials", timeout=None - ): - """Issues a short-lived channel access token. - - https://developers.line.biz/en/reference/messaging-api/#issue-channel-access-token - - :param str client_id: Channel ID. - :param str client_secret: Channel secret. - :param str grant_type: `client_credentials` - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.IssueChannelTokenResponse` - :return: IssueChannelTokenResponse instance - """ - response = await self._post( - "/v2/oauth/accessToken", - data={ - "client_id": client_id, - "client_secret": client_secret, - "grant_type": grant_type, - }, - headers={"Content-Type": "application/x-www-form-urlencoded"}, - timeout=timeout, - ) - - return IssueChannelTokenResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3.oauth import AsyncChannelAccessToken' and 'AsyncChannelAccessToken(...).revoke_channel_token(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def revoke_channel_token(self, access_token, timeout=None): - """Revokes a channel access token. - - https://developers.line.biz/en/reference/messaging-api/#revoke-channel-access-token - - :param str access_token: Channel access token. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._post( - "/v2/oauth/revoke", - data={"access_token": access_token}, - headers={"Content-Type": "application/x-www-form-urlencoded"}, - timeout=timeout, - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_number_of_message_deliveries(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_insight_message_delivery(self, date, timeout=None): - """Get the number of messages sent on a specified day. - - https://developers.line.biz/en/reference/messaging-api/#get-number-of-delivery-messages - - :param str date: Date for which to retrieve number of sent messages. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.InsightMessageDeliveryResponse` - """ - response = await self._get( - "/v2/bot/insight/message/delivery?date={date}".format(date=date), - timeout=timeout, - ) - - return InsightMessageDeliveryResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_insight_followers(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_insight_followers(self, date, timeout=None): - """Get the number of users who have added the bot on or before a specified date. - - https://developers.line.biz/en/reference/messaging-api/#get-number-of-followers - - :param str date: Date for which to retrieve the number of followers. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.InsightFollowersResponse` - """ - response = await self._get( - "/v2/bot/insight/followers?date={date}".format(date=date), timeout=timeout - ) - - return InsightFollowersResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_friends_demographics(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_insight_demographic(self, timeout=None): - """Retrieve the demographic attributes for a bot's friends. - - https://developers.line.biz/en/reference/messaging-api/#get-demographic - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.InsightDemographicResponse` - """ - response = await self._get("/v2/bot/insight/demographic", timeout=timeout) - - return InsightDemographicResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_message_event(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_insight_message_event(self, request_id, timeout=None): - """Return statistics about how users interact with broadcast messages. - - https://developers.line.biz/en/reference/messaging-api/#get-message-event - - :param str request_id: Request ID of broadcast message. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.InsightMessageEventResponse` - """ - response = await self._get( - "/v2/bot/insight/message/event?requestId={request_id}".format( - request_id=request_id - ), - timeout=timeout, - ) - - return InsightMessageEventResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_bot_info(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_bot_info(self, timeout=None): - """Get a bot's basic information. - - https://developers.line.biz/en/reference/messaging-api/#get-bot-info - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.BotInfo` - """ - response = await self._get("/v2/bot/info", timeout=timeout) - - return BotInfo.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).create_audience_group(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def create_audience_group( - self, audience_group_name, audiences=None, is_ifa=False, timeout=None - ): - """Create an audience group. - - https://developers.line.biz/en/reference/messaging-api/#create-upload-audience-group - - :param str audience_group_name: The audience's name - :param list audiences: An array of user IDs or IFAs - :param bool is_ifa: true | false - :return: audience group id - """ - if audiences is None: - audiences = [] - - if audiences: - audiences = [ - Audience.new_from_json_dict(audience) for audience in audiences - ] - response = await self._post( - "/v2/bot/audienceGroup/upload", - data=json.dumps( - { - "description": audience_group_name, - "isIfaAudience": is_ifa, - "audiences": [audience.as_json_dict() for audience in audiences], - } - ), - timeout=timeout, - ) - - return CreateAudienceGroup.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_audience_data(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_audience_group(self, audience_group_id, timeout=None): - """Get the object of audience group. - - https://developers.line.biz/en/reference/messaging-api/#get-audience-group - - :param str audience_group_id: The audience ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :return: AudienceGroup instance - """ - response = await self._get( - "/v2/bot/audienceGroup/{audience_group_id}".format( - audience_group_id=audience_group_id - ), - timeout=timeout, - ) - - return AudienceGroup.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_audience_groups(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_audience_group_list( - self, - page=1, - description=None, - status=None, - size=20, - include_external_public_group=None, - create_route=None, - timeout=None, - ): - """Get data for more than one audience. - - https://developers.line.biz/en/reference/messaging-api/#get-audience-groups - - :param int page: The page to return when getting (paginated) results. Must be 1 or higher - :param str description: The name of the audience(s) to return - :param str status: IN_PROGRESS | READY | FAILED | EXPIRED - :param int size: The number of audiences per page. Default: 20, Max: 40 - :param bool include_external_public_group: true | false - :param str create_route: How the audience was created. - :type create_route: OA_MANAGER | MESSAGING_API - :return: AudienceGroup instance - """ - params = {} - if page: - params["page"] = page - if description: - params["description"] = description - if status: - params["status"] = status - if size: - params["size"] = size - if include_external_public_group: - params["includesExternalPublicGroup"] = include_external_public_group - if create_route: - params["createRoute"] = create_route - response = await self._get( - "/v2/bot/audienceGroup/list?", params=params, timeout=timeout - ) - result = [] - for audience_group in (await response.json).get("audienceGroups", []): - result.append(AudienceGroup.new_from_json_dict(audience_group)) - if (await response.json).get("hasNextPage", False): - result += self.get_audience_group_list( - page + 1, - description, - status, - size, - include_external_public_group, - create_route, - timeout, - ) - return result - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).delete_audience_group(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def delete_audience_group(self, audience_group_id, timeout=None): - """Delete an existing audience. - - https://developers.line.biz/en/reference/messaging-api/#delete-audience-group - - :param str audience_group_id: The audience ID - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._delete( - "/v2/bot/audienceGroup/{}".format(audience_group_id), timeout=timeout - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).update_audience_group_description(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def rename_audience_group(self, audience_group_id, description, timeout=None): - """Modify the name of an existing audience. - - https://developers.line.biz/en/reference/messaging-api/#set-description-audience-group - - :param str audience_group_id: The audience ID - :param str description: The new audience's name - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._put( - "/v2/bot/audienceGroup/{audience_group_id}/updateDescription".format( - audience_group_id=audience_group_id - ), - data=json.dumps( - { - "description": description, - } - ), - timeout=timeout, - ) - - return "" - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).add_audience_to_audience_group(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def add_audiences_to_audience_group( - self, audience_group_id, audiences, upload_description=None, timeout=None - ): - """Add new user IDs or IFAs to an audience for uploading user IDs. - - https://developers.line.biz/en/reference/messaging-api/#update-upload-audience-group - - :param str audience_group_id: The audience ID - :param list audiences: An array of user IDs or IFAs - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :param bool is_ifa: If this is false (default), recipients are specified by user IDs. - If true, recipients must be specified by IFAs. - :param str upload_description: The description to register for the job - :type timeout: float | tuple(float, float) - """ - if audiences: - audiences = [ - Audience.new_from_json_dict(audience) for audience in audiences - ] - response = await self._put( - "/v2/bot/audienceGroup/upload", - data=json.dumps( - { - "audienceGroupId": audience_group_id, - "audiences": [audience.as_json_dict() for audience in audiences], - "uploadDescription": upload_description, - } - ), - timeout=timeout, - ) - - return await response.json - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_audience_group_authority_level(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_audience_group_authority_level(self, timeout=None): - """Get the authority level of the audience. - - https://developers.line.biz/en/reference/messaging-api/#get-authority-level - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :return: json - """ - response = await self._get( - "/v2/bot/audienceGroup/authorityLevel", timeout=timeout - ) - - return GetAuthorityLevel.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).update_audience_group_authority_level(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def change_audience_group_authority_level( - self, authority_level="PUBLIC", timeout=None - ): - """Change the authority level of all audiences created in the same channel. - - https://developers.line.biz/en/reference/messaging-api/#change-authority-level - - :param str authority_level: PUBLIC | PRIVATE. - """ - await self._put( - "/v2/bot/audienceGroup/authorityLevel", - data=json.dumps( - { - "authorityLevel": authority_level, - } - ), - timeout=timeout, - ) - - return "" - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).create_click_based_audience_group(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def create_click_audience_group( - self, description, request_id, click_url=None, timeout=None - ): - """Create an audience for click-based retargeting. - - https://developers.line.biz/en/reference/messaging-api/#create-click-audience-group - - :param str description: The audience's name. Audience names must be unique. - :param str request_id: The request ID of a message sent in the past 60 days. - :param str click_url: The URL clicked by the user. - If empty, users who clicked any URL in the message are added to the list of recipients. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :return: ClickAudienceGroup instance - """ - response = await self._post( - "/v2/bot/audienceGroup/click", - data=json.dumps( - { - "description": description, - "requestId": request_id, - "clickUrl": click_url, - } - ), - timeout=timeout, - ) - - return ClickAudienceGroup.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).create_imp_based_audience_group(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def create_imp_audience_group(self, description, request_id, timeout=None): - """Create an audience for impression-based retargeting. - - https://developers.line.biz/en/reference/messaging-api/#create-imp-audience-group - - :param str description: The audience's name. Audience names must be unique. - :param str request_id: The request ID of a message sent in the past 60 days. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :return: ImpAudienceGroup instance - """ - response = await self._post( - "/v2/bot/audienceGroup/imp", - data=json.dumps( - { - "description": description, - "requestId": request_id, - } - ), - timeout=timeout, - ) - - return ImpAudienceGroup.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).set_webhook_endpoint(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def set_webhook_endpoint(self, webhook_endpoint, timeout=None): - """Set the webhook endpoint URL. - - https://developers.line.biz/en/reference/messaging-api/#set-webhook-endpoint-url - - :param str webhook_endpoint: A valid webhook URL to be set. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: dict - :return: Empty dict. - """ - data = {"endpoint": webhook_endpoint} - - response = await self._put( - "/v2/bot/channel/webhook/endpoint", - data=json.dumps(data), - timeout=timeout, - ) - - return await response.json - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_webhook_endpoint(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_webhook_endpoint(self, timeout=None): - """Get information on a webhook endpoint. - - https://developers.line.biz/en/reference/messaging-api/#get-webhook-endpoint-information - - :rtype: :py:class:`linebot.models.responses.GetWebhookResponse` - :return: Webhook information, including `endpoint` for webhook - URL and `active` for webhook usage status. - """ - response = await self._get( - "/v2/bot/channel/webhook/endpoint", - timeout=timeout, - ) - - return GetWebhookResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).test_webhook_endpoint(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def test_webhook_endpoint(self, webhook_endpoint=None, timeout=None): - """Checks if the configured webhook endpoint can receive a test webhook event. - - https://developers.line.biz/en/reference/messaging-api/#test-webhook-endpoint - - :param webhook_endpoint: (optional) Set this parameter to - specific the webhook endpoint of the webhook. Default is the webhook - endpoint that is already set to the channel. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.TestWebhookResponse` - """ - data = {} - - if webhook_endpoint is not None: - data["endpoint"] = webhook_endpoint - - response = await self._post( - "/v2/bot/channel/webhook/test", - data=json.dumps(data), - timeout=timeout, - ) - - return TestWebhookResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_followers(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_followers_ids(self, limit=300, start=None, timeout=None): - """Get a list of users who added your LINE Official Account as a friend. - - https://developers.line.biz/en/reference/messaging-api/#get-follower-ids - - :param int limit: The maximum number of user IDs to retrieve in a single request. - The default value is 300. - :param str start: Get the next array of user IDs. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.UserIds` - """ - params = {"limit": limit} if start is None else {"limit": limit, "start": start} - - response = await self._get( - "/v2/bot/followers/ids", params=params, timeout=timeout - ) - - return UserIds.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3.oauth import AsyncChannelAccessToken' and 'AsyncChannelAccessToken(...).issue_channel_token_by_jwt(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def issue_channel_access_token_v2_1( - self, - client_assertion, - grant_type="client_credentials", - client_assertion_type="urn:ietf:params:oauth:client-assertion-type:jwt-bearer", - timeout=None, - ): - """Issues a channel access token v2.1. - - https://developers.line.biz/en/reference/messaging-api/#issue-channel-access-token-v2-1 - - :param str client_assertion: Client assertion. - :param str grant_type: `client_credentials` - :param str client_assertion_type: `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.IssueChannelTokenResponseV2` - """ - response = await self._post( - "/oauth2/v2.1/token", - data={ - "grant_type": grant_type, - "client_assertion_type": client_assertion_type, - "client_assertion": client_assertion, - }, - headers={"Content-Type": "application/x-www-form-urlencoded"}, - timeout=timeout, - ) - - return IssueChannelTokenResponseV2.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3.oauth import AsyncChannelAccessToken' and 'AsyncChannelAccessToken(...).revoke_channel_token_by_jwt(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def revoke_channel_access_token_v2_1( - self, client_id, client_secret, access_token, timeout=None - ): - """Revokes a channel access token v2.1. - - https://developers.line.biz/en/reference/messaging-api/#revoke-channel-access-token-v2-1 - - :param str client_id: Client id. - :param str client_secret: Channel secret. - :param str access_token: Channel access token. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - """ - await self._post( - "/oauth2/v2.1/revoke", - data={ - "client_id": client_id, - "client_secret": client_secret, - "access_token": access_token, - }, - timeout=timeout, - ) - - async def get_channel_access_tokens_v2_1( - self, - client_assertion, - client_assertion_type="urn:ietf:params:oauth:client-assertion-type:jwt-bearer", - timeout=None, - ): - """Get issued channel access tokens v2.1. - - https://developers.line.biz/en/reference/messaging-api/#get-issued-channel-access-tokens-v2-1 - - :param str client_assertion: Client assertion. - :param str client_assertion_type: `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.ChannelAccessTokens` - """ - response = await self._get( - "/oauth2/v2.1/tokens", - params={ - "client_assertion": client_assertion, - "client_assertion_type": client_assertion_type, - }, - timeout=timeout, - ) - return ChannelAccessTokens.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3.oauth import AsyncChannelAccessToken' and 'AsyncChannelAccessToken(...).verify_channel_token_by_jwt(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def verify_channel_access_token_v2_1(self, access_token, timeout=None): - """Validate channel access token v2.1. - - https://developers.line.biz/en/reference/messaging-api/#verfiy-channel-access-token-v2-1 - - :param str access_token: Channel access token. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.VerifyChannelTokenResponseV2` - """ - response = await self._get( - "/oauth2/v2.1/verify", - params={"access_token": access_token}, - timeout=timeout, - ) - return VerifyChannelTokenResponseV2.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3.oauth import AsyncChannelAccessToken' and 'AsyncChannelAccessToken(...).gets_all_valid_channel_access_token_key_ids(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_channel_token_key_ids_v2_1( - self, - client_assertion, - client_assertion_type="urn:ietf:params:oauth:client-assertion-type:jwt-bearer", - timeout=None, - ): - """Get all valid channel access token key IDs v2.1. - - https://developers.line.biz/en/reference/messaging-api/#get-all-valid-channel-access-token-key-ids-v2-1 - - :param str client_assertion: Client assertion. - :param str client_assertion_type: `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`. - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class:`linebot.models.responses.VerifyChannelTokenResponseV2` - """ - response = await self._get( - "/oauth2/v2.1/tokens/kid", - params={ - "client_assertion": client_assertion, - "client_assertion_type": client_assertion_type, - }, - timeout=timeout, - ) - return ValidAccessTokenKeyIDsResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_statistics_per_unit(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_statistics_per_unit( - self, custom_aggregation_unit, from_date, to_date, timeout=None - ): - """Return statistics about how users interact with push and multicast messages. - - https://developers.line.biz/en/reference/partner-docs/#get-statistics-per-unit - - :param str custom_aggregation_unit: Name of aggregation unit specified when sending - the message like `push_message(...)` and `multicast(...)`. - :param str from_date: Start date of aggregation period. - The format is `yyyyMMdd` (Timezone is UTC+9). - :param str to_date: End date of aggregation period. - The end date can be specified for up to 30 days later. - The format is `yyyyMMdd` (Timezone is UTC+9). - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class: - `linebot.models.responses.InsightMessageEventOfCustomAggregationUnitResponse` - """ - response = await self._get( - "/v2/bot/insight/message/event/aggregation?" - "customAggregationUnit={custom_aggregation_unit}&from={from_date}&to={to_date}".format( - custom_aggregation_unit=custom_aggregation_unit, - from_date=from_date, - to_date=to_date, - ), - timeout=timeout, - ) - - return InsightMessageEventOfCustomAggregationUnitResponse.new_from_json_dict( - (await response.json) - ) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_aggregation_unit_usage(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_number_of_units_used_this_month(self, timeout=None): - """Return the number of aggregation units used this month. - - https://developers.line.biz/en/reference/partner-docs/#get-number-of-units-used-this-month - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class: `linebot.models.responses.AggregationInfoResponse` - """ - response = await self._get("/v2/bot/message/aggregation/info", timeout=timeout) - return AggregationInfoResponse.new_from_json_dict((await response.json)) - - @deprecated( - reason="Use 'from linebot.v3 import AsyncLineBotClient' and 'AsyncLineBotClient(...).get_aggregation_unit_name_list(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", - version="3.0.0", - category=LineBotSdkDeprecatedIn30, - ) # noqa: E501 - async def get_name_list_of_units_used_this_month( - self, limit=100, start=None, timeout=None - ): - """Return the name list of units used this month for statistics aggregation. - - :param int limit: Maximum number of aggregation units you can get per request. - If you don't specify a value, or if you specify a value greater than or equal to 100, - the maximum is 100. - :param str start: Get the next array of name list of units - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is self.async_http_client.timeout - :type timeout: float | tuple(float, float) - :rtype: :py:class: `linebot.models.responses.AggregationNameListResponse` - """ - params = {"limit": limit} if start is None else {"limit": limit, "start": start} - - response = await self._get( - "/v2/bot/message/aggregation/list", params=params, timeout=timeout - ) - - return AggregationNameListResponse.new_from_json_dict((await response.json)) - - async def _get(self, path, endpoint=None, params=None, headers=None, timeout=None): - url = (endpoint or self.endpoint) + path - - if headers is None: - headers = {} - headers.update(self.headers) - - response = await self.async_http_client.get( - url, headers=headers, params=params, timeout=timeout - ) - - await self.__check_error(response) - return response - - async def _post(self, path, endpoint=None, data=None, headers=None, timeout=None): - url = (endpoint or self.endpoint) + path - - if headers is None: - headers = {"Content-Type": "application/json"} - headers.update(self.headers) - - response = await self.async_http_client.post( - url, headers=headers, data=data, timeout=timeout - ) - - await self.__check_error(response) - return response - - async def _delete(self, path, endpoint=None, data=None, headers=None, timeout=None): - url = (endpoint or self.endpoint) + path - - if headers is None: - headers = {} - headers.update(self.headers) - - response = await self.async_http_client.delete( - url, headers=headers, data=data, timeout=timeout - ) - - await self.__check_error(response) - return response - - async def _put(self, path, endpoint=None, data=None, headers=None, timeout=None): - url = (endpoint or self.endpoint) + path - - if headers is None: - headers = {"Content-Type": "application/json"} - headers.update(self.headers) - - response = await self.async_http_client.put( - url, headers=headers, data=data, timeout=timeout - ) - - await self.__check_error(response) - return response - - @staticmethod - async def __check_error(response): - if 200 <= response.status_code < 300: - pass - else: - raise LineBotApiError( - status_code=response.status_code, - headers=dict(response.headers.items()), - request_id=response.headers.get("X-Line-Request-Id"), - accepted_request_id=response.headers.get("X-Line-Accepted-Request-Id"), - error=Error.new_from_json_dict((await response.json)), - ) diff --git a/linebot/async_http_client.py b/linebot/async_http_client.py deleted file mode 100644 index 75a85f874..000000000 --- a/linebot/async_http_client.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.async_http_client module.""" - -from __future__ import unicode_literals - -from abc import ABCMeta, abstractmethod, abstractproperty - -from future.utils import with_metaclass - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'linebot.v3' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AsyncHttpClient(with_metaclass(ABCMeta)): - """Abstract Base Classes of HttpClient.""" - - DEFAULT_TIMEOUT = 5 - - def __init__(self, timeout=DEFAULT_TIMEOUT): - """__init__ method. - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`DEFAULT_TIMEOUT` - :type timeout: float | tuple(float, float) - :rtype: T <= :py:class:`HttpResponse` - :return: HttpResponse instance - """ - self.timeout = timeout - - @abstractmethod - async def get(self, url, headers=None, params=None, timeout=None): - """GET request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param dict params: (optional) Request query parameter - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: T <= :py:class:`HttpResponse` - :return: HttpResponse instance - """ - raise NotImplementedError - - @abstractmethod - async def post(self, url, headers=None, data=None, timeout=None): - """POST request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param data: (optional) Dictionary, bytes, or file-like object to send in the body - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: T <= :py:class:`HttpResponse` - :return: HttpResponse instance - """ - raise NotImplementedError - - @abstractmethod - async def delete(self, url, headers=None, data=None, timeout=None): - """DELETE request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param data: (optional) Dictionary, bytes, or file-like object to send in the body - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: T <= :py:class:`HttpResponse` - :return: HttpResponse instance - """ - raise NotImplementedError - - @abstractmethod - async def put(self, url, headers=None, data=None, timeout=None): - """PUT request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param data: (optional) Dictionary, bytes, or file-like object to send in the body - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: :py:class:`AsyncHttpResponse` - :return: AsyncHttpResponse instance - """ - raise NotImplementedError - - -@deprecated(reason="Use 'linebot.v3' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AsyncHttpResponse(with_metaclass(ABCMeta)): - """HttpResponse.""" - - @abstractproperty - def status_code(self): - """Get status code.""" - raise NotImplementedError - - @abstractproperty - def headers(self): - """Get headers.""" - raise NotImplementedError - - @abstractproperty - async def text(self): - """Get response body as text-decoded.""" - raise NotImplementedError - - @abstractproperty - async def content(self): - """Get response body as binary.""" - raise NotImplementedError - - @abstractproperty - def json(self): - """Get response body as json-decoded.""" - raise NotImplementedError - - @abstractmethod - def iter_content(self, chunk_size=1024): - """Get response body as iterator content (stream). - - :param int chunk_size: - """ - raise NotImplementedError diff --git a/linebot/constants/__init__.py b/linebot/constants/__init__.py deleted file mode 100644 index 2620cbe94..000000000 --- a/linebot/constants/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.constants package.""" - -from .postback_input_option import PostbackInputOption # noqa diff --git a/linebot/constants/postback_input_option.py b/linebot/constants/postback_input_option.py deleted file mode 100644 index 6d4fc67a1..000000000 --- a/linebot/constants/postback_input_option.py +++ /dev/null @@ -1,26 +0,0 @@ -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.constants.postback_input_option module.""" - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'from linebot.v3.messaging import PostbackAction' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class PostbackInputOption: - """Constant class for Postback input option.""" - - CLOSE_RICH_MENU = "closeRichMenu" - OPEN_RICH_MENU = "openRichMenu" - OPEN_KEYBOARD = "openKeyboard" - OPEN_VOICE = "openVoice" diff --git a/linebot/deprecations.py b/linebot/deprecations.py deleted file mode 100644 index 0282d4007..000000000 --- a/linebot/deprecations.py +++ /dev/null @@ -1,23 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.deprecations module.""" - - -class LineBotSdkDeprecationWarning(DeprecationWarning): - """ My DeprecationWarning """ - - -class LineBotSdkDeprecatedIn30(LineBotSdkDeprecationWarning): - """ deprecated in 3.0 """ diff --git a/linebot/exceptions.py b/linebot/exceptions.py deleted file mode 100644 index d890276ed..000000000 --- a/linebot/exceptions.py +++ /dev/null @@ -1,110 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.exceptions module.""" - -from abc import ABCMeta - -from future.utils import with_metaclass - -from deprecated import deprecated - -from .deprecations import ( - LineBotSdkDeprecatedIn30 -) - - -@deprecated(reason="Use 'linebot.v3' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class BaseError(with_metaclass(ABCMeta, Exception)): - """Base Exception class.""" - - def __init__(self, message='-'): - """__init__ method. - - :param str message: Human readable message - """ - self.message = message - - def __repr__(self): - """repr.""" - return str(self) - - def __str__(self): - """str. - - :rtype: str - """ - return '<{0} [{1}]>'.format( - self.__class__.__name__, self.message) - - -@deprecated(reason="Use 'from linebot.v3.exceptions import InvalidSignatureError' and v3 webhook handlers instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class InvalidSignatureError(BaseError): - """When Webhook signature does NOT match, this error will be raised.""" - - def __init__(self, message='-'): - """__init__ method. - - :param str message: Human readable message - """ - super(InvalidSignatureError, self).__init__(message) - - -@deprecated(reason="Use 'from linebot.v3.messaging.exceptions import ApiException' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class LineBotApiError(BaseError): - """When LINE Messaging API response error, this error will be raised.""" - - def __init__( - self, - status_code, - headers, - request_id=None, - accepted_request_id=None, - error=None - ): - """__init__ method. - - :param int status_code: HTTP status code - :param headers: Response headers - :type headers: dict[str, str] - :param str request_id: (optional) Request ID. A unique ID is generated for each request - :param str accepted_request_id: (optional) The same request has already been accepted - :param error: (optional) Error class object. - :type error: :py:class:`linebot.models.error.Error` - """ - super(LineBotApiError, self).__init__(error.message) - - self.status_code = status_code - self.headers = headers - self.request_id = request_id - self.accepted_request_id = accepted_request_id - self.error = error - - def __str__(self): - """str. - - :rtype: str - """ - if self.accepted_request_id: - return "{0}: status_code={1}, request_id={2}, " \ - "accepted_request_id={3}, error_response={4}, headers={5}" \ - .format(self.__class__.__name__, - self.status_code, - self.request_id, - self.accepted_request_id, - self.error, - self.headers) - return '{0}: status_code={1}, request_id={2}, error_response={3}, headers={4}'.format( - self.__class__.__name__, self.status_code, self.request_id, self.error, - self.headers) diff --git a/linebot/http_client.py b/linebot/http_client.py deleted file mode 100644 index 1b63aefe1..000000000 --- a/linebot/http_client.py +++ /dev/null @@ -1,309 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.http_client module.""" - - -from abc import ABCMeta, abstractmethod, abstractproperty - -import requests -from future.utils import with_metaclass - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'linebot.v3' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class HttpClient(with_metaclass(ABCMeta)): - """Abstract Base Classes of HttpClient.""" - - DEFAULT_TIMEOUT = 5 - - def __init__(self, timeout=DEFAULT_TIMEOUT): - """__init__ method. - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`DEFAULT_TIMEOUT` - :type timeout: float | tuple(float, float) - :rtype: T <= :py:class:`HttpResponse` - :return: HttpResponse instance - """ - self.timeout = timeout - - @abstractmethod - def get(self, url, headers=None, params=None, stream=False, timeout=None): - """GET request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param dict params: (optional) Request query parameter - :param bool stream: (optional) get content as stream - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: T <= :py:class:`HttpResponse` - :return: HttpResponse instance - """ - raise NotImplementedError - - @abstractmethod - def post(self, url, headers=None, data=None, timeout=None): - """POST request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param data: (optional) Dictionary, bytes, or file-like object to send in the body - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: T <= :py:class:`HttpResponse` - :return: HttpResponse instance - """ - raise NotImplementedError - - @abstractmethod - def delete(self, url, headers=None, data=None, timeout=None): - """DELETE request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param data: (optional) Dictionary, bytes, or file-like object to send in the body - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: T <= :py:class:`HttpResponse` - :return: HttpResponse instance - """ - raise NotImplementedError - - @abstractmethod - def put(self, url, headers=None, data=None, timeout=None): - """PUT request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param data: (optional) Dictionary, bytes, or file-like object to send in the body - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: :py:class:`RequestsHttpResponse` - :return: RequestsHttpResponse instance - """ - raise NotImplementedError - - -@deprecated(reason="Use 'linebot.v3' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class RequestsHttpClient(HttpClient): - """HttpClient implemented by requests.""" - - def __init__(self, timeout=HttpClient.DEFAULT_TIMEOUT): - """__init__ method. - - :param timeout: (optional) How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`DEFAULT_TIMEOUT` - :type timeout: float | tuple(float, float) - """ - super(RequestsHttpClient, self).__init__(timeout) - - def get(self, url, headers=None, params=None, stream=False, timeout=None): - """GET request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param dict params: (optional) Request query parameter - :param bool stream: (optional) get content as stream - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: :py:class:`RequestsHttpResponse` - :return: RequestsHttpResponse instance - """ - if timeout is None: - timeout = self.timeout - - response = requests.get( - url, headers=headers, params=params, stream=stream, timeout=timeout - ) - - return RequestsHttpResponse(response) - - def post(self, url, headers=None, data=None, timeout=None): - """POST request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param data: (optional) Dictionary, bytes, or file-like object to send in the body - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: :py:class:`RequestsHttpResponse` - :return: RequestsHttpResponse instance - """ - if timeout is None: - timeout = self.timeout - - response = requests.post( - url, headers=headers, data=data, timeout=timeout - ) - - return RequestsHttpResponse(response) - - def delete(self, url, headers=None, data=None, timeout=None): - """DELETE request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param data: (optional) Dictionary, bytes, or file-like object to send in the body - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: :py:class:`RequestsHttpResponse` - :return: RequestsHttpResponse instance - """ - if timeout is None: - timeout = self.timeout - - response = requests.delete( - url, headers=headers, data=data, timeout=timeout - ) - - return RequestsHttpResponse(response) - - def put(self, url, headers=None, data=None, timeout=None): - """PUT request. - - :param str url: Request url - :param dict headers: (optional) Request headers - :param data: (optional) Dictionary, bytes, or file-like object to send in the body - :param timeout: (optional), How long to wait for the server - to send data before giving up, as a float, - or a (connect timeout, read timeout) float tuple. - Default is :py:attr:`self.timeout` - :type timeout: float | tuple(float, float) - :rtype: :py:class:`RequestsHttpResponse` - :return: RequestsHttpResponse instance - """ - if timeout is None: - timeout = self.timeout - - response = requests.put( - url, headers=headers, data=data, timeout=timeout - ) - - return RequestsHttpResponse(response) - - -@deprecated(reason="Use 'linebot.v3' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class HttpResponse(with_metaclass(ABCMeta)): - """HttpResponse.""" - - @abstractproperty - def status_code(self): - """Get status code.""" - raise NotImplementedError - - @abstractproperty - def headers(self): - """Get headers.""" - raise NotImplementedError - - @abstractproperty - def text(self): - """Get response body as text-decoded.""" - raise NotImplementedError - - @abstractproperty - def content(self): - """Get response body as binary.""" - raise NotImplementedError - - @abstractproperty - def json(self): - """Get response body as json-decoded.""" - raise NotImplementedError - - @abstractmethod - def iter_content(self, chunk_size=1024, decode_unicode=False): - """Get response body as iterator content (stream). - - :param int chunk_size: - :param bool decode_unicode: - """ - raise NotImplementedError - - -@deprecated(reason="Use 'linebot.v3' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class RequestsHttpResponse(HttpResponse): - """HttpResponse implemented by requests lib's response.""" - - def __init__(self, response): - """__init__ method. - - :param response: requests lib's response - """ - self.response = response - - @property - def status_code(self): - """Get status code.""" - return self.response.status_code - - @property - def headers(self): - """Get headers. - - :rtype :py:class:`requests.models.CaseInsensitiveDict` - """ - return self.response.headers - - @property - def text(self): - """Get response body as text-decoded.""" - return self.response.text - - @property - def content(self): - """Get response body as binary.""" - return self.response.content - - @property - def json(self): - """Get response body as json-decoded.""" - return self.response.json() - - def iter_content(self, chunk_size=1024, decode_unicode=False): - """Get response body as iterator content (stream). - - :param int chunk_size: - :param bool decode_unicode: - """ - return self.response.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode) diff --git a/linebot/models/__init__.py b/linebot/models/__init__.py deleted file mode 100644 index a5e05c48a..000000000 --- a/linebot/models/__init__.py +++ /dev/null @@ -1,224 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models package.""" - -from .actions import ( # noqa - Action, - PostbackAction, - MessageAction, - URIAction, - DatetimePickerAction, - CameraAction, - CameraRollAction, - LocationAction, - RichMenuSwitchAction, - Action as TemplateAction, # backward compatibility - PostbackAction as PostbackTemplateAction, # backward compatibility - MessageAction as MessageTemplateAction, # backward compatibility - URIAction as URITemplateAction, # backward compatibility - DatetimePickerAction as DatetimePickerTemplateAction, # backward compatibility - AltUri, -) -from .base import ( # noqa - Base, -) -from .error import ( # noqa - Error, - ErrorDetail, -) -from .events import ( # noqa - Event, - MessageEvent, - FollowEvent, - UnfollowEvent, - JoinEvent, - LeaveEvent, - PostbackEvent, - AccountLinkEvent, - MemberJoinedEvent, - MemberLeftEvent, - BeaconEvent, - ThingsEvent, - UnknownEvent, - Postback, - Beacon, - Link, - VideoPlayCompleteEvent, - UnsendEvent, -) -from .filter import ( # noqa - Filter, - DemographicFilter, - GenderFilter, - AppTypeFilter, - AreaFilter, - AgeFilter, - SubscriptionPeriodFilter, -) - -from .flex_message import ( # noqa - FlexSendMessage, - FlexContainer, - BubbleContainer, - BubbleStyle, - BlockStyle, - CarouselContainer, - FlexComponent, - BoxComponent, - ButtonComponent, - FillerComponent, - IconComponent, - ImageComponent, - SeparatorComponent, - TextComponent, - SpanComponent, - VideoComponent -) -from .imagemap import ( # noqa - ImagemapSendMessage, - BaseSize, - ImagemapAction, - URIImagemapAction, - MessageImagemapAction, - ImagemapArea, - Video, - ExternalLink, -) -from .insight import ( # noqa - DemographicInsight, - AgeInsight, - AreaInsight, - AppTypeInsight, - GenderInsight, - SubscriptionPeriodInsight, - MessageStatistics, - MessageInsight, - ClickInsight, - JobInsight, -) - -from .limit import ( # noqa - Limit, -) - -from .messages import ( # noqa - Message, - TextMessage, - ImageMessage, - VideoMessage, - AudioMessage, - LocationMessage, - StickerMessage, - FileMessage, -) - -from .operator import ( # noqa - And, - Or, - Not -) - -from .recipient import ( # noqa - AudienceRecipient, - RedeliveryRecipient -) - -from .responses import ( # noqa - Profile, - MemberIds, - Content, - RichMenuResponse, - MessageQuotaResponse, - MessageQuotaConsumptionResponse, - MessageDeliveryBroadcastResponse, - MessageDeliveryReplyResponse, - MessageDeliveryMulticastResponse, - MessageDeliveryPushResponse, - Content as MessageContent, # backward compatibility, - IssueLinkTokenResponse, - IssueChannelTokenResponse, - InsightMessageDeliveryResponse, - InsightFollowersResponse, - InsightDemographicResponse, - InsightMessageEventResponse, - BroadcastResponse, - NarrowcastResponse, - ValidateReplyMessageObjectsResponse, - ValidatePushMessageObjectsResponse, - ValidateMulticastMessageObjectsResponse, - ValidateBroadcastMessageObjectsResponse, - ValidateNarrowcastMessageObjectsResponse, - MessageProgressNarrowcastResponse, - BotInfo, - GetWebhookResponse, - TestWebhookResponse, - AudienceGroup, - ClickAudienceGroup, - ImpAudienceGroup, - GetAuthorityLevel, - Audience, - CreateAudienceGroup, -) -from .rich_menu import ( # noqa - RichMenu, - RichMenuSize, - RichMenuArea, - RichMenuBounds, - RichMenuAlias, -) -from .send_messages import ( # noqa - SendMessage, - TextSendMessage, - ImageSendMessage, - VideoSendMessage, - AudioSendMessage, - LocationSendMessage, - StickerSendMessage, - QuickReply, - QuickReplyButton, - Sender, -) -from .sources import ( # noqa - Source, - SourceUser, - SourceGroup, - SourceRoom, -) -from .template import ( # noqa - TemplateSendMessage, - Template, - ButtonsTemplate, - ConfirmTemplate, - CarouselTemplate, - CarouselColumn, - ImageCarouselTemplate, - ImageCarouselColumn, -) -from .things import ( # noqa - DeviceLink, - DeviceUnlink, - ScenarioResult, - ActionResult, - Things, -) - -from .background import ( # noqa - Background, - LinearGradientBackground, -) - -from .emojis import ( # noqa - Emojis -) diff --git a/linebot/models/actions.py b/linebot/models/actions.py deleted file mode 100644 index 696cda1ee..000000000 --- a/linebot/models/actions.py +++ /dev/null @@ -1,326 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.actions module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -def get_action(action): - """Get action.""" - action_obj = Base.get_or_new_from_json_dict_with_types( - action, { - 'postback': PostbackAction, - 'message': MessageAction, - 'uri': URIAction, - 'datetimepicker': DatetimePickerAction, - 'camera': CameraAction, - 'cameraRoll': CameraRollAction, - 'location': LocationAction, - 'richmenuswitch': RichMenuSwitchAction, - } - ) - return action_obj - - -def get_actions(actions): - """Get actions.""" - new_actions = [] - if actions: - for action in actions: - action_obj = get_action(action) - if action_obj: - new_actions.append(action_obj) - - return new_actions - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Action(with_metaclass(ABCMeta, Base)): - """Abstract base class of Action.""" - - def __init__(self, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(Action, self).__init__(**kwargs) - - self.type = None - - -@deprecated(reason="Use 'from linebot.v3.messaging import PostbackAction' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class PostbackAction(Action): - """PostbackAction. - - https://developers.line.me/en/docs/messaging-api/reference/#postback-action - - When a control associated with this action is tapped, - a postback event is returned via webhook with the specified string in the data property. - """ - - def __init__( - self, - label=None, - data=None, - display_text=None, - text=None, - input_option=None, - fill_in_text=None, - **kwargs - ): - """__init__ method. - - :param str label: Label for the action. - :param str data: String returned via webhook - in the postback.data property of the postback event. - :param str display_text: Text displayed in the chat as a message sent by - the user when the action is performed. - :param str text: Deprecated. Text displayed in the chat as a message sent by - the user when the action is performed. Returned from the server through a webhook. - :param kwargs: - """ - super(PostbackAction, self).__init__(**kwargs) - - self.type = 'postback' - self.label = label - self.data = data - self.display_text = display_text - self.text = text - self.input_option = input_option - self.fill_in_text = fill_in_text - - -@deprecated(reason="Use 'from linebot.v3.messaging import MessageAction' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MessageAction(Action): - """MessageAction. - - https://developers.line.me/en/docs/messaging-api/reference/#message-action - - When a control associated with this action is tapped, - the string in the text property is sent as a message from the user. - """ - - def __init__(self, label=None, text=None, **kwargs): - """__init__ method. - - :param str label: Label for the action. - :param str text: Text sent when the action is performed. - :param kwargs: - """ - super(MessageAction, self).__init__(**kwargs) - - self.type = 'message' - self.label = label - self.text = text - - -@deprecated(reason="Use 'from linebot.v3.messaging import URIAction' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class URIAction(Action): - """URIAction. - - https://developers.line.me/en/docs/messaging-api/reference/#uri-action - - When a control associated with this action is tapped, - the URI specified in the uri property is opened. - """ - - def __init__(self, label=None, uri=None, alt_uri=None, **kwargs): - """__init__ method. - - :param str label: Label for the action - Max: 20 characters - :param str uri: URI opened when the action is performed. - :param alt_uri: URI opened when the desktop app. - :type alt_uri: T <= :py:class:`linebot.models.actions.AltUri` - :param kwargs: - """ - super(URIAction, self).__init__(**kwargs) - - self.type = 'uri' - self.label = label - self.uri = uri - self.alt_uri = self.get_or_new_from_json_dict(alt_uri, AltUri) - - -@deprecated(reason="Use 'from linebot.v3.messaging import AltUri' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AltUri(with_metaclass(ABCMeta, Base)): - """AltUri. - - https://github.com/line/line-bot-sdk-python/issues/155 - - URI opened when the desktop app. - """ - - def __init__(self, desktop=None, **kwargs): - """__init__ method. - - :param str desktop: URI opened on LINE for macOS and Windows - when the action is performed. - If the altUri.desktop property is set, - the uri property is ignored on LINE for macOS and Windows. - :param kwargs: - """ - super(AltUri, self).__init__(**kwargs) - - self.desktop = desktop - - -@deprecated(reason="Use 'from linebot.v3.messaging import DatetimePickerAction' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class DatetimePickerAction(Action): - """DatetimePickerAction. - - https://developers.line.me/en/docs/messaging-api/reference/#datetime-picker-action - - When a control associated with this action is tapped, - a postback event is returned via webhook with the date and time - selected by the user from the date and time selection dialog. - The datetime picker action does not support time zones. - """ - - def __init__(self, label=None, data=None, mode=None, - initial=None, max=None, min=None, **kwargs): - """__init__ method. - - :param str label: Label for the action - :param str data: String returned via webhook - in the postback.data property of the postback event - :param str mode: Action mode - date: Pick date - time: Pick time - datetime: Pick date and time - :param str initial: Initial value of date or time - :param str max: Largest date or time value that can be selected. - Must be greater than the min value. - :param str min: Smallest date or time value that can be selected. - Must be less than the max value. - :param kwargs: - """ - super(DatetimePickerAction, self).__init__(**kwargs) - - self.type = 'datetimepicker' - self.label = label - self.data = data - self.mode = mode - self.initial = initial - self.max = max - self.min = min - - -@deprecated(reason="Use 'from linebot.v3.messaging import CameraAction' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class CameraAction(Action): - """CameraAction. - - https://developers.line.me/en/reference/messaging-api/#camera-action - - This action can be configured only with quick reply buttons. - When a button associated with this action is tapped, - the camera screen in the LINE app is opened. - """ - - def __init__(self, label=None, **kwargs): - """__init__ method. - - :param str label: Label for the action - :param kwargs: - """ - super(CameraAction, self).__init__(**kwargs) - - self.type = 'camera' - self.label = label - - -@deprecated(reason="Use 'from linebot.v3.messaging import CameraRollAction' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class CameraRollAction(Action): - """CameraRollAction. - - https://developers.line.me/en/reference/messaging-api/#camera-roll-action - - This action can be configured only with quick reply buttons. - When a button associated with this action is tapped, - the camera roll screen in the LINE app is opened. - """ - - def __init__(self, label=None, **kwargs): - """__init__ method. - - :param str label: Label for the action - :param kwargs: - """ - super(CameraRollAction, self).__init__(**kwargs) - - self.type = 'cameraRoll' - self.label = label - - -@deprecated(reason="Use 'from linebot.v3.messaging import LocationAction' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class LocationAction(Action): - """LocationRollAction. - - https://developers.line.me/en/reference/messaging-api/#location-action - - This action can be configured only with quick reply buttons. - When a button associated with this action is tapped, - the location screen in the LINE app is opened. - """ - - def __init__(self, label=None, **kwargs): - """__init__ method. - - :param str label: Label for the action - :param kwargs: - """ - super(LocationAction, self).__init__(**kwargs) - - self.type = 'location' - self.label = label - - -@deprecated(reason="Use 'from linebot.v3.messaging import RichMenuSwitchAction' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class RichMenuSwitchAction(Action): - """RichMenuSwitchAction. - - https://developers.line.biz/en/reference/messaging-api/#richmenu-switch-action - - This action can be configured only with rich menus. - It can't be used for Flex Messages or quick replies. - When you tap a rich menu associated with this action, - you can switch between rich menus, - and a postback event including the rich menu alias ID selected - by the user is returned via a webhook. - """ - - def __init__(self, label=None, rich_menu_alias_id=None, data=None, **kwargs): - """__init__ method. - - :param str label: Label for the action - :param str rich_menu_alias_id: Rich menu alias ID to switch to. - :param str data: String returned by the postback.data property - of the postback event via a webhook - :param kwargs: - """ - super(RichMenuSwitchAction, self).__init__(**kwargs) - - self.type = 'richmenuswitch' - self.label = label - self.rich_menu_alias_id = rich_menu_alias_id - self.data = data diff --git a/linebot/models/background.py b/linebot/models/background.py deleted file mode 100644 index 0411aa6db..000000000 --- a/linebot/models/background.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.emojis module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Background(with_metaclass(ABCMeta, Base)): - """Background.""" - - def __init__(self, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(Background, self).__init__(**kwargs) - - self.type = None - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexBoxLinearGradient' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class LinearGradientBackground(Background): - """LinearGradientBackground.""" - - def __init__(self, angle, start_color, end_color, - center_color=None, center_position=None, **kwargs): - """__init__ method. - - :param str type: The type of background used - :param str angle: The angle at which a linear gradient moves - :param str start_color: The color at the gradient's starting point - :param str end_color: The color at the gradient's ending point - :param str center_color: The color in the middle of the gradient - :param str center_position: The position of the intermediate color stop - :param kwargs: - """ - super(LinearGradientBackground, self).__init__(**kwargs) - self.type = 'linearGradient' - self.angle = angle - self.start_color = start_color - self.end_color = end_color - self.center_color = center_color - self.center_position = center_position diff --git a/linebot/models/base.py b/linebot/models/base.py deleted file mode 100644 index 164fca9d9..000000000 --- a/linebot/models/base.py +++ /dev/null @@ -1,145 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.base module.""" - - -import json - -from .. import utils - - -class Base(object): - """Base class of model. - - Suitable for JSON base data. - """ - - def __init__(self, **kwargs): - """__init__ method. - - :param kwargs: - """ - pass - - def __str__(self): - """__str__ method.""" - return self.as_json_string() - - def __repr__(self): - """__repr__ method.""" - return str(self) - - def __eq__(self, other): - """__eq__ method. - - :param other: - """ - return other and self.as_json_dict() == other.as_json_dict() - - def __ne__(self, other): - """__ne__ method. - - :param other: - """ - return not self.__eq__(other) - - def as_json_string(self): - """Return JSON string from this object. - - :rtype: str - """ - return json.dumps(self.as_json_dict(), sort_keys=True) - - def as_json_dict(self): - """Return dictionary from this object. - - :return: dict - """ - data = {} - for key, value in self.__dict__.items(): - camel_key = utils.to_camel_case(key) - if isinstance(value, (list, tuple, set)): - data[camel_key] = list() - for item in value: - if hasattr(item, 'as_json_dict'): - data[camel_key].append(item.as_json_dict()) - else: - data[camel_key].append(item) - - elif hasattr(value, 'as_json_dict'): - data[camel_key] = value.as_json_dict() - elif value is not None: - data[camel_key] = value - - return data - - @classmethod - def new_from_json_dict(cls, data, use_raw_message=False): - """Create a new instance from a dict. - - :param data: JSON dict - :param bool use_raw_message: Using original Message key as attribute - """ - if use_raw_message: - return cls(use_raw_message=use_raw_message, **data) - - new_data = {utils.to_snake_case(key): value - for key, value in data.items()} - - return cls(**new_data) - - @staticmethod - def get_or_new_from_json_dict(data, cls): - """Get `cls` object w/ deserialization from json if needed. - - If data is instance of cls, return data. - Else if data is instance of dict, create instance from dict. - Else, return None. - - :param data: - :param cls: - :rtype: object - """ - if isinstance(data, cls): - return data - elif isinstance(data, dict): - return cls.new_from_json_dict(data) - - return None - - @staticmethod - def get_or_new_from_json_dict_with_types( - data, cls_map, type_key='type', use_raw_message=False - ): - """Get `cls` object w/ deserialization from json by using type key hint if needed. - - If data is instance of one of cls, return data. - Else if data is instance of dict, create instance from dict. - Else, return None. - - :param data: - :param cls_map: - :param type_key: - :rtype: object - :param bool use_raw_message: Using original Message key as attribute - """ - if isinstance(data, tuple(cls_map.values())): - return data - elif isinstance(data, dict): - type_val = data[type_key] - if type_val in cls_map: - return cls_map[type_val].new_from_json_dict(data, use_raw_message=use_raw_message) - - return None diff --git a/linebot/models/delivery_context.py b/linebot/models/delivery_context.py deleted file mode 100644 index 644a33b44..000000000 --- a/linebot/models/delivery_context.py +++ /dev/null @@ -1,42 +0,0 @@ -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.delivery_context module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - - -from deprecated import deprecated - -from linebot.deprecations import ( - LineBotSdkDeprecatedIn30 -) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import DeliveryContext' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class DeliveryContext(with_metaclass(ABCMeta, Base)): - """Abstract Base Class of DeliveryContext.""" - - def __init__(self, is_redelivery=None, **kwargs): - """__init__ method. - - :param bool is_redelivery: Whether the webhook event is a redelivered one or not - :param kwargs: - """ - super(DeliveryContext, self).__init__(**kwargs) - - self.is_redelivery = is_redelivery diff --git a/linebot/models/emojis.py b/linebot/models/emojis.py deleted file mode 100644 index ea6952839..000000000 --- a/linebot/models/emojis.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.emojis module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'from linebot.v3.messaging import Emoji' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Emojis(with_metaclass(ABCMeta, Base)): - """Emojis. - - https://developers.line.biz/en/reference/messaging-api/#text-message - - """ - - def __init__(self, index=None, length=None, product_id=None, emoji_id=None, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(Emojis, self).__init__(**kwargs) - - self.index = index - self.length = length - self.product_id = product_id - self.emoji_id = emoji_id diff --git a/linebot/models/error.py b/linebot/models/error.py deleted file mode 100644 index a8ece4d6e..000000000 --- a/linebot/models/error.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.error module.""" - - -from .base import Base - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'from linebot.v3.messaging import ErrorResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Error(Base): - """Error response of LINE messaging API. - - https://developers.line.biz/en/reference/messaging-api/#error-response - """ - - def __init__(self, message=None, details=None, **kwargs): - """__init__ method. - - :param str message: Summary of the error - :param details: ErrorDetail instance list - :type details: list[T <= :py:class:`linebot.models.error.ErrorDetail`] - :param kwargs: - """ - super(Error, self).__init__(**kwargs) - - self.message = message - - new_details = [] - if details: - for detail in details: - new_details.append( - self.get_or_new_from_json_dict(detail, ErrorDetail) - ) - self.details = new_details - - -@deprecated(reason="Use 'from linebot.v3.messaging import ErrorDetail' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ErrorDetail(Base): - """ErrorDetail response of LINE messaging API.""" - - def __init__(self, message=None, property=None, **kwargs): - """__init__ method. - - :param str message: Details of the error message - :param str property: Related property - :param kwargs: - """ - super(ErrorDetail, self).__init__(**kwargs) - - self.message = message - self.property = property diff --git a/linebot/models/events.py b/linebot/models/events.py deleted file mode 100644 index 15eacf654..000000000 --- a/linebot/models/events.py +++ /dev/null @@ -1,647 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.events module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from linebot.models.base import Base -from linebot.models.delivery_context import DeliveryContext -from linebot.models.messages import ( - TextMessage, - ImageMessage, - VideoMessage, - AudioMessage, - LocationMessage, - StickerMessage, - FileMessage -) -from linebot.models.sources import SourceUser, SourceGroup, SourceRoom -from linebot.models.things import ( - DeviceUnlink, - DeviceLink, - ScenarioResult, -) -from linebot.models.things import Things # noqa, backward compatibility -from linebot.models.unsend import Unsend -from linebot.models.video_play_complete import VideoPlayComplete - -from deprecated import deprecated - -from deprecated import deprecated - -from linebot.deprecations import ( - LineBotSdkDeprecatedIn30 -) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import VideoPlayComplete' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Event(with_metaclass(ABCMeta, Base)): - """Abstract Base Class of Webhook Event. - - https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects - """ - - def __init__( - self, - mode=None, - timestamp=None, - source=None, - webhook_event_id=None, - delivery_context=None, - **kwargs - ): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param kwargs: - """ - super(Event, self).__init__(**kwargs) - - self.type = None - self.mode = mode - self.timestamp = timestamp - self.source = self.get_or_new_from_json_dict_with_types( - source, { - 'user': SourceUser, - 'group': SourceGroup, - 'room': SourceRoom, - } - ) - self.webhook_event_id = webhook_event_id - self.delivery_context = self.get_or_new_from_json_dict( - delivery_context, DeliveryContext - ) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import MessageEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MessageEvent(Event): - """Webhook MessageEvent. - - https://developers.line.biz/en/reference/messaging-api/#message-event - - Event object which contains the sent message. - The message field contains a message object which corresponds with the message type. - You can reply to message events. - """ - - def __init__(self, mode=None, timestamp=None, source=None, reply_token=None, message=None, - use_raw_message=False, **kwargs): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param str reply_token: Reply token - :param message: Message object - :type message: T <= :py:class:`linebot.models.messages.Message` - :param bool use_raw_message: Using original Message key as attribute - :param kwargs: - """ - super(MessageEvent, self).__init__( - mode=mode, timestamp=timestamp, source=source, **kwargs - ) - - self.type = 'message' - self.reply_token = reply_token - self.message = self.get_or_new_from_json_dict_with_types( - message, { - 'text': TextMessage, - 'image': ImageMessage, - 'video': VideoMessage, - 'audio': AudioMessage, - 'location': LocationMessage, - 'sticker': StickerMessage, - 'file': FileMessage - }, use_raw_message=use_raw_message - ) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import FollowEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class FollowEvent(Event): - """Webhook FollowEvent. - - https://developers.line.biz/en/reference/messaging-api/#follow-event - - Event object for when your account is added as a friend (or unblocked). - You can reply to follow events. - """ - - def __init__(self, mode=None, timestamp=None, source=None, reply_token=None, **kwargs): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param str reply_token: Reply token - :param kwargs: - """ - super(FollowEvent, self).__init__( - mode=mode, timestamp=timestamp, source=source, **kwargs - ) - - self.type = 'follow' - self.reply_token = reply_token - - -@deprecated(reason="Use 'from linebot.v3.webhooks import UnfollowEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class UnfollowEvent(Event): - """Webhook UnfollowEvent. - - https://developers.line.biz/en/reference/messaging-api/#unfollow-event - - Event object for when your account is blocked. - """ - - def __init__(self, mode=None, timestamp=None, source=None, **kwargs): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param kwargs: - """ - super(UnfollowEvent, self).__init__( - mode=mode, timestamp=timestamp, source=source, **kwargs - ) - - self.type = 'unfollow' - - -@deprecated(reason="Use 'from linebot.v3.webhooks import JoinEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class JoinEvent(Event): - """Webhook JoinEvent. - - https://developers.line.biz/en/reference/messaging-api/#join-event - - Event object for when your account joins a group or talk room. - You can reply to join events. - """ - - def __init__(self, mode=None, timestamp=None, source=None, reply_token=None, **kwargs): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param str reply_token: Reply token - :param kwargs: - """ - super(JoinEvent, self).__init__( - mode=mode, timestamp=timestamp, source=source, **kwargs - ) - - self.type = 'join' - self.reply_token = reply_token - - -@deprecated(reason="Use 'from linebot.v3.webhooks import LeaveEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class LeaveEvent(Event): - """Webhook LeaveEvent. - - https://developers.line.biz/en/reference/messaging-api/#leave-event - - Event object for when your account leaves a group. - """ - - def __init__(self, mode=None, timestamp=None, source=None, **kwargs): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param kwargs: - """ - super(LeaveEvent, self).__init__( - mode=mode, timestamp=timestamp, source=source, **kwargs - ) - - self.type = 'leave' - - -@deprecated(reason="Use 'from linebot.v3.webhooks import PostbackEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class PostbackEvent(Event): - """Webhook PostbackEvent. - - https://developers.line.biz/en/reference/messaging-api/#postback-event - - Event object for when a user performs an action on - a template message which initiates a postback. - You can reply to postback events. - """ - - def __init__(self, mode=None, timestamp=None, source=None, reply_token=None, postback=None, - **kwargs): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param str reply_token: Reply token - :param postback: Postback object - :type postback: :py:class:`linebot.models.events.Postback` - :param kwargs: - """ - super(PostbackEvent, self).__init__( - mode=mode, timestamp=timestamp, source=source, **kwargs - ) - - self.type = 'postback' - self.reply_token = reply_token - self.postback = self.get_or_new_from_json_dict( - postback, Postback - ) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import BeaconEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class BeaconEvent(Event): - """Webhook BeaconEvent. - - https://developers.line.biz/en/reference/messaging-api/#beacon-event - - Event object for when a user detects a LINE Beacon. You can reply to beacon events. - """ - - def __init__(self, mode=None, timestamp=None, source=None, reply_token=None, beacon=None, - **kwargs): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param str reply_token: Reply token - :param beacon: Beacon object - :type beacon: :py:class:`linebot.models.events.Beacon` - :param kwargs: - """ - super(BeaconEvent, self).__init__( - mode=mode, timestamp=timestamp, source=source, **kwargs - ) - - self.type = 'beacon' - self.reply_token = reply_token - self.beacon = self.get_or_new_from_json_dict( - beacon, Beacon - ) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import MemberJoinedEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MemberJoinedEvent(Event): - """Webhook MemberJoinedEvent. - - https://developers.line.biz/en/reference/messaging-api/#member-joined-event - - Event object for when a user joins a group or room that the bot is in. - - """ - - def __init__(self, mode=None, timestamp=None, source=None, reply_token=None, joined=None, - **kwargs): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param str reply_token: Reply token - :param joined: Joined object - :type joined: :py:class:`linebot.models.events.Joined` - :param kwargs: - """ - super(MemberJoinedEvent, self).__init__( - mode=mode, timestamp=timestamp, source=source, **kwargs - ) - - self.type = 'memberJoined' - self.reply_token = reply_token - self.joined = self.get_or_new_from_json_dict( - joined, Joined - ) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import MemberLeftEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MemberLeftEvent(Event): - """Webhook MemberLeftEvent. - - https://developers.line.biz/en/reference/messaging-api/#member-left-event - - Event object for when a user leaves a group or room that the bot is in. - - """ - - def __init__(self, mode=None, timestamp=None, source=None, left=None, **kwargs): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param left: Left object - :type left: :py:class:`linebot.models.events.Left` - :param kwargs: - """ - super(MemberLeftEvent, self).__init__( - mode=mode, timestamp=timestamp, source=source, **kwargs - ) - - self.type = 'memberLeft' - self.left = self.get_or_new_from_json_dict( - left, Left - ) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import AccountLinkEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AccountLinkEvent(Event): - """Webhook AccountLinkEvent. - - https://developers.line.me/en/docs/messaging-api/reference/#account-link-event - - Event object for when a user has linked his/her LINE account with a provider's service account. - You can reply to account link events. - If the link token has expired or has already been used, - no webhook event will be sent and the user will be shown an error. - """ - - def __init__(self, mode=None, timestamp=None, source=None, reply_token=None, link=None, - **kwargs): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param str reply_token: Reply token - :param link: Link object - :type link: :py:class:`linebot.models.events.Link` - :param kwargs: - """ - super(AccountLinkEvent, self).__init__( - mode=mode, timestamp=timestamp, source=source, **kwargs - ) - - self.type = 'accountLink' - self.reply_token = reply_token - self.link = self.get_or_new_from_json_dict( - link, Link - ) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import ThingsEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ThingsEvent(Event): - """Webhook ThingsEvent. - - https://developers.line.biz/en/reference/messaging-api/#device-link-event - https://developers.line.biz/en/reference/messaging-api/#device-unlink-event - https://developers.line.biz/en/reference/messaging-api/#scenario-result-event - - Event sent from LINE Things Webhook service. - """ - - def __init__(self, mode=None, timestamp=None, source=None, reply_token=None, things=None, - **kwargs): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param str reply_token: Reply token - :param things: Things object - :type things: T <= :py:class:`linebot.models.things.Things` - :param kwargs: - """ - super(ThingsEvent, self).__init__( - mode=mode, timestamp=timestamp, source=source, **kwargs - ) - - self.type = 'things' - self.reply_token = reply_token - self.things = self.get_or_new_from_json_dict_with_types( - things, { - 'link': DeviceLink, - 'unlink': DeviceUnlink, - 'scenarioResult': ScenarioResult, - } - ) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import UnsendEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class UnsendEvent(Event): - """Webhook UnsendEvent. - - https://developers.line.biz/en/reference/messaging-api/#unsend-event - - Event object for when the user unsends a message in a group or room. - """ - - def __init__(self, mode=None, timestamp=None, source=None, unsend=None, **kwargs): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param unsend: Unsend object - :type unsend: T <= :py:class:`linebot.models.unsend.Unsend` - :param kwargs: - """ - super(UnsendEvent, self).__init__( - mode=mode, timestamp=timestamp, source=source, **kwargs - ) - - self.type = 'unsend' - self.unsend = self.get_or_new_from_json_dict( - unsend, Unsend - ) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import VideoPlayCompleteEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class VideoPlayCompleteEvent(Event): - """Webhook VideoCompleteEvent. - - https://developers.line.biz/en/reference/messaging-api/#video-viewing-complete - - Event object Event for when a user finishes viewing a video at least once. - """ - - def __init__(self, mode=None, timestamp=None, source=None, reply_token=None, - video_play_complete=None, **kwargs): - """__init__ method. - - :param str mode: Channel state - :param long timestamp: Time of the event in milliseconds - :param source: Source object - :type source: T <= :py:class:`linebot.models.sources.Source` - :param str reply_token: Reply token - :param video_play_complete: VideoPlayComplete object - :type video_play_complete: - T <= :py:class:`linebot.models.video_play_complete.VideoPlayComplete` - :param kwargs: - """ - super(VideoPlayCompleteEvent, self).__init__( - mode=mode, timestamp=timestamp, source=source, **kwargs - ) - - self.type = 'videoPlayComplete' - self.reply_token = reply_token - self.video_play_complete = self.get_or_new_from_json_dict( - video_play_complete, VideoPlayComplete - ) - - -@deprecated(reason="Use 'from linebot.v3.models import UnknownEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class UnknownEvent(Event): - """Unknown event. - - We welcome your contribution to line-bot-sdk-python! - """ - - def __init__(self, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(UnknownEvent, self).__init__(**kwargs) - - self.type = 'unknown' - - -@deprecated(reason="Use 'from linebot.v3.webhooks import PostbackContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Postback(Base): - """Postback. - - https://developers.line.biz/en/reference/messaging-api/#postback-event - """ - - def __init__(self, data=None, params=None, **kwargs): - """__init__ method. - - :param str data: Postback data - :param dict params: JSON object with the date and time - selected by a user through a datetime picker action. - Only returned for postback actions via the datetime picker. - :param kwargs: - """ - super(Postback, self).__init__(**kwargs) - - self.data = data - self.params = params - - -@deprecated(reason="Use 'from linebot.v3.webhooks import BeaconContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Beacon(Base): - """Beacon. - - https://developers.line.biz/en/reference/messaging-api/#beacon-event - """ - - def __init__(self, type=None, hwid=None, dm=None, **kwargs): - """__init__ method. - - :param str type: Type of beacon event - :param str hwid: Hardware ID of the beacon that was detected - :param str dm: Optional. Device message of beacon which is hex string - :param kwargs: - """ - super(Beacon, self).__init__(**kwargs) - - self.type = type - self.hwid = hwid - self.dm = dm - - @property - def device_message(self): - """Get dm(device_message) as bytearray. - - :rtype: bytearray - """ - return bytearray.fromhex(self.dm) if self.dm is not None else None - - -@deprecated(reason="Use 'from linebot.v3.webhooks import JoinedMembers' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Joined(Base): - """Joined. - - https://developers.line.biz/en/reference/messaging-api/#member-joined-event - """ - - def __init__(self, members=None, **kwargs): - """__init__ method. - - :param dict members: Member of users who joined - :param kwargs: - """ - super(Joined, self).__init__(**kwargs) - - self._members = members - - @property - def members(self): - """Get members as list of SourceUser.""" - return [SourceUser(user_id=x['userId']) for x in self._members] - - -@deprecated(reason="Use 'from linebot.v3.webhooks import LeftMembers' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Left(Base): - """Left. - - https://developers.line.biz/en/reference/messaging-api/#member-left-event - """ - - def __init__(self, members=None, **kwargs): - """__init__ method. - - :param dict members: Member of users who joined - :param kwargs: - """ - super(Left, self).__init__(**kwargs) - - self._members = members - - @property - def members(self): - """Get members as list of SourceUser.""" - return [SourceUser(user_id=x['userId']) for x in self._members] - - -@deprecated(reason="Use 'from linebot.v3.webhooks import AccountLinkEvent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Link(Base): - """Link. - - https://developers.line.me/en/docs/messaging-api/reference/#link-object - """ - - def __init__(self, result=None, nonce=None, **kwargs): - """__init__ method. - - :param str result: Indicate whether the link was successful or not. - :param str nonce: Specified nonce when verifying the user ID. - """ - super(Link, self).__init__(**kwargs) - - self.result = result - self.nonce = nonce diff --git a/linebot/models/filter.py b/linebot/models/filter.py deleted file mode 100644 index b4f718259..000000000 --- a/linebot/models/filter.py +++ /dev/null @@ -1,183 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.filter module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Filter(with_metaclass(ABCMeta, Base)): - """Filter. - - https://developers.line.biz/en/reference/messaging-api/#narrowcast-demographic-filter - - A filter is the top-level structure of a demographic element. - """ - - def __init__(self, demographic=None, **kwargs): - """__init__ method. - - :param demographic: Combination of different criteria using logical - operator objects. - :type demographic: :py:class:`linebot.model.filter.DemographicFilter` | - :py:class:`linebot.model.operator.Operator` - :param kwargs: - """ - super(Filter, self).__init__(**kwargs) - - self.demographic = demographic - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class DemographicFilter(Filter): - """DemographicFilter. - - https://developers.line.biz/en/reference/messaging-api/#narrowcast-demographic-filter - - Demographic filter objects represent criteria (e.g. age, gender, OS, region, - and friendship duration) on which to filter the list of recipients. - You can filter recipients based on a combination of different criteria using - logical operator objects. - """ - - def __init__(self, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(DemographicFilter, self).__init__(**kwargs) - - self.type = None - - -@deprecated(reason="Use 'from linebot.v3.messaging import GenderDemographicFilter' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class GenderFilter(DemographicFilter): - """GenderFilter.""" - - def __init__(self, one_of=None, **kwargs): - """__init__ method. - - :param one_of: Send messages to users of a given gender. One of: - male: Users who identify as male - female: Users who identify as female - :type one_of: list[str] - """ - super(GenderFilter, self).__init__(**kwargs) - - if one_of is None: - one_of = [] - - self.type = "gender" - self.one_of = one_of - - -@deprecated(reason="Use 'from linebot.v3.messaging import AppTypeDemographicFilter' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AppTypeFilter(DemographicFilter): - """AppTypeFilter.""" - - def __init__(self, one_of=None, **kwargs): - """__init__ method. - - :param one_of: Send messages to users of the specified OS. One of: - ios: Users who using iOS. - android: Users who using Android. - :type one_of: list[str] - """ - super(AppTypeFilter, self).__init__(**kwargs) - - if one_of is None: - one_of = [] - - self.type = "appType" - self.one_of = one_of - - -@deprecated(reason="Use 'from linebot.v3.messaging import AreaDemographicFilter' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AreaFilter(DemographicFilter): - """AreaFilter.""" - - def __init__(self, one_of=None, **kwargs): - """__init__ method. - - :param one_of: Send messages to users in the specified region. - :type one_of: list[str] - """ - super(AreaFilter, self).__init__(**kwargs) - - if one_of is None: - one_of = [] - - self.type = "area" - self.one_of = one_of - - -@deprecated(reason="Use 'from linebot.v3.messaging import AgeDemographicFilter' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AgeFilter(DemographicFilter): - """AgeFilter. - - This lets you filter recipients with a given age range. - """ - - def __init__(self, gte=None, lt=None, **kwargs): - """__init__ method. - - Be sure to specify either gte, lt, or both. - - :param gte: Send messages to users at least as old as the specified age. - :type gte: str - :param lt: Send messages to users younger than the specified age. - You can specify the same values as for the gte property. - :type lt: str - """ - super(AgeFilter, self).__init__(**kwargs) - - self.type = "age" - self.gte = gte - self.lt = lt - - -@deprecated(reason="Use 'from linebot.v3.messaging import SubscriptionPeriodDemographicFilter' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class SubscriptionPeriodFilter(DemographicFilter): - """SubscriptionPeriodFilter. - - This lets you filter recipients with a given range of friendship durations. - """ - - def __init__(self, gte=None, lt=None, **kwargs): - """__init__ method. - - Be sure to specify either gte, lt, or both. - - :param gte: Send messages to users who have been friends of yours for - at least the specified number of days - :type gte: str - :param lt: Send messages to users who have been friends of yours for - less than the specified number of days. - You can specify the same values as for the gte property. - :type lt: str - """ - super(SubscriptionPeriodFilter, self).__init__(**kwargs) - - self.type = "subscriptionPeriod" - self.gte = gte - self.lt = lt diff --git a/linebot/models/flex_message.py b/linebot/models/flex_message.py deleted file mode 100644 index 7a2c92ccd..000000000 --- a/linebot/models/flex_message.py +++ /dev/null @@ -1,752 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.flex_message module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .background import Background, LinearGradientBackground -from .actions import get_action -from .base import Base -from .send_messages import SendMessage - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexMessage' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class FlexSendMessage(SendMessage): - """FlexSendMessage. - - https://developers.line.biz/en/reference/messaging-api/#flex-message - - Flex Messages are messages with a customizable layout. - You can customize the layout freely by combining multiple elements. - """ - - def __init__(self, alt_text=None, contents=None, **kwargs): - """__init__ method. - - :param str alt_text: Alternative text - :param contents: Flex Message container object - :type contents: :py:class:`linebot.models.flex_message.FlexContainer` - :param kwargs: - """ - super(FlexSendMessage, self).__init__(**kwargs) - - self.type = 'flex' - self.alt_text = alt_text - self.contents = self.get_or_new_from_json_dict_with_types( - contents, { - 'bubble': BubbleContainer, - 'carousel': CarouselContainer - } - ) - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class FlexContainer(with_metaclass(ABCMeta, Base)): - """FlexContainer. - - https://developers.line.biz/en/reference/messaging-api/#container - - A container is the top-level structure of a Flex Message. - """ - - def __init__(self, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(FlexContainer, self).__init__(**kwargs) - - self.type = None - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexBubble' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class BubbleContainer(FlexContainer): - """BubbleContainer. - - https://developers.line.biz/en/reference/messaging-api/#bubble - - This is a container that contains one message bubble. - It can contain four blocks: header, hero, body, and footer. - """ - - def __init__(self, size=None, direction=None, header=None, hero=None, - body=None, footer=None, styles=None, action=None, **kwargs): - """__init__ method. - - :param str size: The size of the bubble. `nano`, `micro`, `kilo`, `mega`, or `giga`. - :param str direction: Text directionality and the order of components - in horizontal boxes in the container - :param header: Header block - :type header: :py:class:`linebot.models.flex_message.BoxComponent` - :param hero: Hero block - :type hero: :py:class:`linebot.models.flex_message.ImageComponent` - | :py:class:`linebot.models.flex_message.BoxComponent` - | :py:class:`linebot.models.flex_message.VideoComponent` - :param body: Body block - :type body: :py:class:`linebot.models.flex_message.BoxComponent` - :param footer: Footer block - :type footer: :py:class:`linebot.models.flex_message.BoxComponent` - :param styles: Style of each block - :type styles: :py:class:`linebot.models.flex_message.BubbleStyle` - :param action: Action performed when this button is tapped - :type action: list[T <= :py:class:`linebot.models.actions.Action`] - :param kwargs: - """ - super(BubbleContainer, self).__init__(**kwargs) - - self.type = 'bubble' - self.size = size - self.direction = direction - self.header = self.get_or_new_from_json_dict(header, BoxComponent) - self.hero = self.get_or_new_from_json_dict_with_types( - hero, { - 'image': ImageComponent, - 'box': BoxComponent, - 'video': VideoComponent - } - ) - self.body = self.get_or_new_from_json_dict(body, BoxComponent) - self.footer = self.get_or_new_from_json_dict(footer, BoxComponent) - self.styles = self.get_or_new_from_json_dict(styles, BubbleStyle) - self.action = get_action(action) - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexBubbleStyles' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class BubbleStyle(with_metaclass(ABCMeta, Base)): - """BubbleStyle. - - https://developers.line.biz/en/reference/messaging-api/#bubble-style - """ - - def __init__(self, header=None, hero=None, body=None, footer=None, **kwargs): - """__init__ method. - - :param header: Style of the header block - :type header: :py:class:`linebot.models.flex_message.BlockStyle` - :param hero: Style of the hero block - :type hero: :py:class:`linebot.models.flex_message.BlockStyle` - :param body: Style of the body block - :type body: :py:class:`linebot.models.flex_message.BlockStyle` - :param footer: Style of the footer block - :type footer: :py:class:`linebot.models.flex_message.BlockStyle` - :param kwargs: - """ - super(BubbleStyle, self).__init__(**kwargs) - - self.header = self.get_or_new_from_json_dict(header, BlockStyle) - self.hero = self.get_or_new_from_json_dict(hero, BlockStyle) - self.body = self.get_or_new_from_json_dict(body, BlockStyle) - self.footer = self.get_or_new_from_json_dict(footer, BlockStyle) - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexBlockStyle' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class BlockStyle(with_metaclass(ABCMeta, Base)): - """BlockStyle. - - https://developers.line.biz/en/reference/messaging-api/#block-style - """ - - def __init__(self, background_color=None, separator=None, separator_color=None, **kwargs): - """__init__ method. - - :param str background_color: Background color of the block. Use a hexadecimal color code - :param bool separator: True to place a separator above the block - True will be ignored for the first block in a container - because you cannot place a separator above the first block. - The default value is False - :param str separator_color: Color of the separator. Use a hexadecimal color code - :param kwargs: - """ - super(BlockStyle, self).__init__(**kwargs) - self.background_color = background_color - self.separator = separator - self.separator_color = separator_color - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexCarousel' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class CarouselContainer(FlexContainer): - """CarouselContainer. - - https://developers.line.biz/en/reference/messaging-api/#f-carousel - - This is a container that contains multiple bubble containers, or message bubbles. - The bubbles will be shown in order by scrolling horizontally. - """ - - def __init__(self, contents=None, **kwargs): - """__init__ method. - - :param contents: Array of bubble containers - :type contents: list[T <= :py:class:`linebot.models.flex_message.BubbleContainer`] - :param kwargs: - """ - super(CarouselContainer, self).__init__(**kwargs) - - self.type = 'carousel' - - new_contents = [] - if contents: - for it in contents: - new_contents.append(self.get_or_new_from_json_dict( - it, BubbleContainer - )) - self.contents = new_contents - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class FlexComponent(with_metaclass(ABCMeta, Base)): - """FlexComponent. - - https://developers.line.biz/en/reference/messaging-api/#component - - Components are objects that compose a Flex Message container. - """ - - def __init__(self, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(FlexComponent, self).__init__(**kwargs) - - self.type = None - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexBox' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class BoxComponent(FlexComponent): - """BoxComponent. - - https://developers.line.biz/en/reference/messaging-api/#box - - This is a component that defines the layout of child components. - You can also include a box in a box. - """ - - def __init__(self, - layout=None, - contents=None, - background_color=None, - border_color=None, - border_width=None, - corner_radius=None, - justify_content=None, - align_items=None, - background=None, - width=None, - max_width=None, - height=None, - max_height=None, - flex=None, - spacing=None, - margin=None, - padding_all=None, - padding_top=None, - padding_bottom=None, - padding_start=None, - padding_end=None, - position=None, - offset_top=None, - offset_bottom=None, - offset_start=None, - offset_end=None, - action=None, - **kwargs): - """__init__ method. - - :param str layout: The placement style of components in this box - :param contents: Components in this box - :type contents: list[T <= :py:class:`linebot.models.flex_message.FlexComponent`] - :param str background_color: Background color of the block - :param str border_color: Color of box border - :param str border_width: Width of box border - :param str corner_radius: Radius at the time of rounding the corners of the border - :param str justify_content: How child elements are aligned along the main axis of - the parent element - :param str align_items: How child elements are aligned along the cross axis of - the parent element - :param background: Background object - :type background: T <= :py:class:`linebot.models.background.Background` - :param str width: Width of the box - :param str max_width: Maximum width of the box - :param str height: Height of the box - :param str max_height: Maximum height of the box - :param float flex: The ratio of the width or height of this box within the parent box - and the previous component in the parent box - :param str spacing: Minimum space between components in this box - :param str margin: Minimum space between this box - :param str padding_all: Free space between the borders of this box and the child element - :param str padding_top: Free space between the border at the upper end of this box - and the upper end of the child element - :param str padding_bottom: Free space between the border at the lower end of this box - and the lower end of the child element - :param str padding_start: Free space between the border at the left end of this box - and the left end of the child element - :param str padding_end: Free space between the border at the right end of this box - and the right end of the child element - :param str position: Reference position for placing this box - :param str offset_top: The top offset - :param str offset_bottom: The bottom offset - :param str offset_start: The left offset - :param str offset_end: The right offset - :param action: Action performed when this button is tapped - :type action: list[T <= :py:class:`linebot.models.actions.Action`] - :param kwargs: - """ - super(BoxComponent, self).__init__(**kwargs) - self.type = 'box' - self.layout = layout - self.background_color = background_color - self.border_color = border_color - self.border_width = border_width - self.corner_radius = corner_radius - self.justify_content = justify_content - self.align_items = align_items - self.width = width - self.max_width = max_width - self.height = height - self.max_height = max_height - self.flex = flex - self.spacing = spacing - self.margin = margin - self.padding_all = padding_all - self.padding_top = padding_top - self.padding_bottom = padding_bottom - self.padding_start = padding_start - self.padding_end = padding_end - self.position = position - self.offset_top = offset_top - self.offset_bottom = offset_bottom - self.offset_start = offset_start - self.offset_end = offset_end - self.action = get_action(action) - self.background = Background.get_or_new_from_json_dict_with_types( - background, {'linearGradient': LinearGradientBackground} - ) - - new_contents = [] - if contents: - for it in contents: - new_contents.append(self.get_or_new_from_json_dict_with_types( - it, { - 'box': BoxComponent, - 'button': ButtonComponent, - 'filler': FillerComponent, - 'icon': IconComponent, - 'image': ImageComponent, - 'span': SpanComponent, - 'separator': SeparatorComponent, - 'text': TextComponent, - 'video': VideoComponent - } - )) - self.contents = new_contents - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexButton' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ButtonComponent(FlexComponent): - """ButtonComponent. - - https://developers.line.biz/en/reference/messaging-api/#button - - This component draws a button. - When the user taps a button, a specified action is performed. - """ - - def __init__(self, - action=None, - flex=None, - margin=None, - position=None, - offset_top=None, - offset_bottom=None, - offset_start=None, - offset_end=None, - height=None, - style=None, - color=None, - gravity=None, - adjust_mode=None, - **kwargs): - """__init__ method. - - :param action: Action performed when this button is tapped - :type action: list[T <= :py:class:`linebot.models.actions.Action`] - :param float flex: The ratio of the width or height of this component within the parent box - :param str margin: Minimum space between this component - and the previous component in the parent box - :param str position: Reference position for placing this box - :param str offset_top: The top offset - :param str offset_bottom: The bottom offset - :param str offset_start: The left offset - :param str offset_end: The right offset - :param str height: Height of the button - :param str style: Style of the button - :param str color: Character color when the style property is link. - Background color when the style property is primary or secondary. - Use a hexadecimal color code - :param str gravity: Vertical alignment style - :param str adjust_mode: The method by which to adjust the text font size - :param kwargs: - """ - super(ButtonComponent, self).__init__(**kwargs) - self.type = 'button' - self.action = get_action(action) - self.flex = flex - self.margin = margin - self.position = position - self.offset_top = offset_top - self.offset_bottom = offset_bottom - self.offset_start = offset_start - self.offset_end = offset_end - self.height = height - self.style = style - self.color = color - self.gravity = gravity - self.adjust_mode = adjust_mode - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexFiller' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class FillerComponent(FlexComponent): - """FillerComponent. - - https://developers.line.biz/en/reference/messaging-api/#filler - - This is an invisible component to fill extra space between components. - """ - - def __init__(self, flex=None, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(FillerComponent, self).__init__(**kwargs) - self.type = 'filler' - self.flex = flex - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexIcon' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class IconComponent(FlexComponent): - """IconComponent. - - https://developers.line.biz/en/reference/messaging-api/#icon - - This component draws an icon. - """ - - def __init__(self, - url=None, - margin=None, - position=None, - offset_top=None, - offset_bottom=None, - offset_start=None, - offset_end=None, - size=None, - aspect_ratio=None, - **kwargs): - """__init__ method. - - :param str url: Image URL - Protocol: HTTPS - Image format: JPEG or PNG - :param str margin: Minimum space between this component - and the previous component in the parent box - :param str position: Reference position for placing this box - :param str offset_top: The top offset - :param str offset_bottom: The bottom offset - :param str offset_start: The left offset - :param str offset_end: The right offset - :param str size: Maximum size of the icon width - :param str aspect_ratio: Aspect ratio of the icon - :param kwargs: - """ - super(IconComponent, self).__init__(**kwargs) - self.type = 'icon' - self.url = url - self.margin = margin - self.position = position - self.offset_top = offset_top - self.offset_bottom = offset_bottom - self.offset_start = offset_start - self.offset_end = offset_end - self.size = size - self.aspect_ratio = aspect_ratio - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexImage' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ImageComponent(FlexComponent): - """ImageComponent. - - https://developers.line.biz/en/reference/messaging-api/#f-image - - This component draws an image. - """ - - def __init__(self, - url=None, - flex=None, - margin=None, - position=None, - offset_top=None, - offset_bottom=None, - offset_start=None, - offset_end=None, - align=None, - gravity=None, - size=None, - aspect_ratio=None, - aspect_mode=None, - background_color=None, - action=None, - animated=False, - **kwargs): - """__init__ method. - - :param str url: Image URL - Protocol: HTTPS - Image format: JPEG or PNG - :param float flex: The ratio of the width or height of this component within the parent box - :param str margin: Minimum space between this component - and the previous component in the parent box - :param str position: Reference position for placing this box - :param str offset_top: The top offset - :param str offset_bottom: The bottom offset - :param str offset_start: The left offset - :param str offset_end: The right offset - :param str align: Horizontal alignment style - :param str gravity: Vertical alignment style - :param str size: Maximum size of the image width - :param str aspect_ratio: Aspect ratio of the image - :param str aspect_mode: Style of the image - :param str background_color: Background color of the image. Use a hexadecimal color code. - :param action: Action performed when this image is tapped - :type action: list[T <= :py:class:`linebot.models.actions.Action`] - :param bool animated: True to play an animated image. Default is False. - :param kwargs: - """ - super(ImageComponent, self).__init__(**kwargs) - self.type = 'image' - self.url = url - self.flex = flex - self.margin = margin - self.position = position - self.offset_top = offset_top - self.offset_bottom = offset_bottom - self.offset_start = offset_start - self.offset_end = offset_end - self.align = align - self.gravity = gravity - self.size = size - self.aspect_ratio = aspect_ratio - self.aspect_mode = aspect_mode - self.background_color = background_color - self.action = get_action(action) - self.animated = animated - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexSeparator' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class SeparatorComponent(FlexComponent): - """SeparatorComponent. - - https://developers.line.biz/en/reference/messaging-api/#separator - - This component draws a separator between components in the parent box. - """ - - def __init__(self, margin=None, color=None, **kwargs): - """__init__ method. - - :param str margin: Minimum space between this component - and the previous component in the parent box - :param str color: Color of the separator. Use a hexadecimal color code - :param kwargs: - """ - super(SeparatorComponent, self).__init__(**kwargs) - self.type = 'separator' - self.margin = margin - self.color = color - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexSpan' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class SpanComponent(FlexComponent): - """SpanComponent. - - https://developers.line.biz/en/reference/messaging-api/#span - - This component renders multiple text strings with different designs in one row. - """ - - def __init__(self, - text=None, - color=None, - size=None, - weight=None, - style=None, - decoration=None, - **kwargs): - r"""__init__ method. - - :param str text: Text - :param str color: Font color - :param str size: Font size - :param str weight: Font weight - :param str style: Style of the text - :param str decoration: Decoration of the text - :param kwargs: - """ - super(SpanComponent, self).__init__(**kwargs) - self.type = 'span' - self.text = text - self.size = size - self.weight = weight - self.color = color - self.style = style - self.decoration = decoration - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexText' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class TextComponent(FlexComponent): - """TextComponent. - - https://developers.line.biz/en/reference/messaging-api/#f-text - - This component draws text. You can format the text. - """ - - def __init__(self, - text=None, - contents=None, - flex=None, - margin=None, - position=None, - offset_top=None, - offset_bottom=None, - offset_start=None, - offset_end=None, - size=None, - align=None, - gravity=None, - wrap=None, - line_spacing=None, - max_lines=None, - weight=None, - color=None, - action=None, - style=None, - decoration=None, - **kwargs): - r"""__init__ method. - - :param str text: Text - :param contents: Array of spans - :type contents: list[T <= :py:class:`linebot.models.flex_message.SpanComponent`] - :param float flex: The ratio of the width or height of this component within the parent box - :param str margin: Minimum space between this component - and the previous component in the parent box - :param str position: Reference position for placing this box - :param str offset_top: The top offset - :param str offset_bottom: The bottom offset - :param str offset_start: The left offset - :param str offset_end: The right offset - :param str size: Font size - :param str align: Horizontal alignment style - :param str gravity: Vertical alignment style - :param bool wrap: rue to wrap text. The default value is False. - If set to True, you can use a new line character (\n) to begin on a new line. - :param str line_spacing: Line spacing in a wrapping text - :param int max_lines: Max number of lines - :param str weight: Font weight - :param str color: Font color - :param action: Action performed when this image is tapped - :type action: list[T <= :py:class:`linebot.models.actions.Action`] - :param str style: Style of the text - :param str decoration: Decoration of the text - :param kwargs: - """ - super(TextComponent, self).__init__(**kwargs) - self.type = 'text' - self.text = text - self.flex = flex - self.margin = margin - self.position = position - self.offset_top = offset_top - self.offset_bottom = offset_bottom - self.offset_start = offset_start - self.offset_end = offset_end - self.size = size - self.align = align - self.gravity = gravity - self.wrap = wrap - self.line_spacing = line_spacing - self.max_lines = max_lines - self.weight = weight - self.color = color - self.action = get_action(action) - self.style = style - self.decoration = decoration - - if contents: - self.contents = [self.get_or_new_from_json_dict(it, SpanComponent) for it in contents] - else: - self.contents = None - - -@deprecated(reason="Use 'from linebot.v3.messaging import FlexVideo' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class VideoComponent(FlexComponent): - """VideoComponent. - - https://developers.line.biz/en/reference/messaging-api/#f-video - - This component renders a video. - """ - - def __init__(self, - url=None, - preview_url=None, - alt_content=None, - aspect_ratio=None, - action=None, - **kwargs): - r"""__init__ method. - - :param str url: URL of video file - :param str preview_url: URL of preview image - :param alt_content: Alternative content - :type alt_content: :py:class:`linebot.models.flex_message.ImageComponent` - | :py:class:`linebot.models.flex_message.BoxComponent` - :param float aspect_ratio: Aspect ratio of the video - :param action: Action performed when this video is tapped - :type action: list[T <= :py:class:`linebot.models.actions.Action`] - :param kwargs: - """ - super(VideoComponent, self).__init__(**kwargs) - - self.type = 'video' - self.url = url - self.preview_url = preview_url - self.alt_content = self.get_or_new_from_json_dict_with_types( - alt_content, { - 'image': ImageComponent, - 'box': BoxComponent - } - ) - self.aspect_ratio = aspect_ratio - self.action = get_action(action) diff --git a/linebot/models/imagemap.py b/linebot/models/imagemap.py deleted file mode 100644 index 3b4b4d7ff..000000000 --- a/linebot/models/imagemap.py +++ /dev/null @@ -1,237 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.imagemap module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base -from .send_messages import SendMessage - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'from linebot.v3.messaging import ImagemapMessage' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ImagemapSendMessage(SendMessage): - """ImagemapSendMessage. - - https://developers.line.biz/en/reference/messaging-api/#imagemap-message - - Imagemaps are images with one or more links. You can assign one link for the entire image - or multiple links which correspond to different regions of the image. - """ - - def __init__(self, base_url=None, alt_text=None, base_size=None, - video=None, actions=None, **kwargs): - """__init__ method. - - :param str base_url: Base URL of image. - HTTPS - :param str alt_text: Alternative text - :param base_size: Width and height of base image - :type base_size: :py:class:`linebot.models.imagemap.BaseSize` - :param video: Video in imagemap message - :type video: :py:class:`linebot.models.imagemap.Video` - :param actions: Action when tapped - :type actions: list[T <= :py:class:`linebot.models.imagemap.ImagemapAction`] - :param kwargs: - """ - super(ImagemapSendMessage, self).__init__(**kwargs) - - self.type = 'imagemap' - self.base_url = base_url - self.alt_text = alt_text - self.base_size = self.get_or_new_from_json_dict( - base_size, BaseSize - ) - self.video = self.get_or_new_from_json_dict( - video, Video - ) - - new_actions = [] - if actions: - for action in actions: - action_obj = self.get_or_new_from_json_dict_with_types( - action, { - 'uri': URIImagemapAction, - 'message': MessageImagemapAction - } - ) - if action_obj: - new_actions.append(action_obj) - self.actions = new_actions - - -@deprecated(reason="Use 'from linebot.v3.messaging import ImagemapBaseSize' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class BaseSize(Base): - """BaseSize. - - https://developers.line.biz/en/reference/messaging-api/#imagemap-message - """ - - def __init__(self, width=None, height=None, **kwargs): - """__init__ method. - - :param int width: Width of base image (set to 1040px) - :param int height: Height of base image(set to the height - that corresponds to a width of 1040px - :param kwargs: - """ - super(BaseSize, self).__init__(**kwargs) - - self.width = width - self.height = height - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ImagemapAction(with_metaclass(ABCMeta, Base)): - """ImagemapAction. - - https://developers.line.biz/en/reference/messaging-api/#imagemap-message - """ - - def __init__(self, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(ImagemapAction, self).__init__(**kwargs) - - self.type = None - - -@deprecated(reason="Use 'from linebot.v3.messaging import URIImagemapAction' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class URIImagemapAction(ImagemapAction): - """URIImagemapAction. - - https://developers.line.biz/en/reference/messaging-api/#imagemap-message - """ - - def __init__(self, link_uri=None, area=None, **kwargs): - """__init__ method. - - :param str link_uri: Webpage URL - :param area: Defined tappable area - :type area: :py:class:`linebot.models.imagemap.ImagemapArea` - :param kwargs: - """ - super(URIImagemapAction, self).__init__(**kwargs) - - self.type = 'uri' - self.link_uri = link_uri - self.area = self.get_or_new_from_json_dict(area, ImagemapArea) - - -@deprecated(reason="Use 'from linebot.v3.messaging import MessageImagemapAction' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MessageImagemapAction(ImagemapAction): - """MessageImagemapAction. - - https://developers.line.biz/en/reference/messaging-api/#imagemap-message - """ - - def __init__(self, text=None, area=None, **kwargs): - """__init__ method. - - :param str text: Message to send - :param area: Defined tappable area - :type area: :py:class:`linebot.models.imagemap.ImagemapArea` - :param kwargs: - """ - super(MessageImagemapAction, self).__init__(**kwargs) - - self.type = 'message' - self.text = text - self.area = self.get_or_new_from_json_dict(area, ImagemapArea) - - -@deprecated(reason="Use 'from linebot.v3.messaging import ImagemapArea' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ImagemapArea(Base): - """ImagemapArea. - - https://developers.line.biz/en/reference/messaging-api/#imagemap-area-object - - Defines the size of the full imagemap with the width as 1040px. - The top left is used as the origin of the area. - """ - - def __init__(self, x=None, y=None, width=None, height=None, **kwargs): - """__init__ method. - - :param int x: Horizontal position of the tappable area - :param int y: Vertical position of the tappable area - :param int width: Width of the tappable area - :param int height: Height of the tappable area - :param kwargs: - """ - super(ImagemapArea, self).__init__(**kwargs) - - self.x = x - self.y = y - self.width = width - self.height = height - - -@deprecated(reason="Use 'from linebot.v3.messaging import ImagemapVideo' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Video(Base): - """Video. - - https://developers.line.biz/en/reference/messaging-api/#imagemap-message - - Defines the properties of the video object in imagemap. - """ - - def __init__(self, original_content_url=None, preview_image_url=None, - area=None, external_link=None, **kwargs): - """__init__ method. - - :param str original_content_url: URL of the video file - :param str preview_image_url: URL of the preview image - :param area: Defined video area - :type area: :py:class:`linebot.models.imagemap.ImagemapArea` - :param external_link: Defined video external link - :type external_link: :py:class:`linebot.models.imagemap.ExternalLink` - :param kwargs: - """ - super(Video, self).__init__(**kwargs) - - self.original_content_url = original_content_url - self.preview_image_url = preview_image_url - self.area = self.get_or_new_from_json_dict(area, ImagemapArea) - self.external_link = self.get_or_new_from_json_dict(external_link, ExternalLink) - - -@deprecated(reason="Use 'from linebot.v3.messaging import ImagemapExternalLink' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ExternalLink(Base): - """ExternalLink. - - https://developers.line.biz/en/reference/messaging-api/#imagemap-message - - Defines URL and label of external link in video. - """ - - def __init__(self, link_uri=None, label=None, **kwargs): - """__init__ method. - - :param str link_uri: Webpage URL - :param str label: Label - :param kwargs: - """ - super(ExternalLink, self).__init__(**kwargs) - - self.link_uri = link_uri - self.label = label diff --git a/linebot/models/insight.py b/linebot/models/insight.py deleted file mode 100644 index 3c7c5eb04..000000000 --- a/linebot/models/insight.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.insight module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'linebot.v3.insight' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class DemographicInsight(with_metaclass(ABCMeta, Base)): - """Abstract Base Class of DemographicInsight.""" - - def __init__(self, percentage=None, **kwargs): - """__init__ method. - - :param float percentage: Percentage. - :param kwargs: - """ - super(DemographicInsight, self).__init__(**kwargs) - self.percentage = percentage - - -@deprecated(reason="Use 'linebot.v3.insight' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class GenderInsight(DemographicInsight): - """GenderInsight.""" - - def __init__(self, percentage=None, gender=None, **kwargs): - """__init__ method. - - :param float percentage: Percentage. - :param str gender: Gender - :param kwargs: - """ - super(GenderInsight, self).__init__(percentage=percentage, **kwargs) - - self.gender = gender - - -@deprecated(reason="Use 'linebot.v3.insight' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AgeInsight(DemographicInsight): - """AgeInsight.""" - - def __init__(self, percentage=None, age=None, **kwargs): - """__init__ method. - - :param float percentage: Percentage. - :param str age: Age - :param kwargs: - """ - super(AgeInsight, self).__init__(percentage=percentage, **kwargs) - - self.age = age - - -@deprecated(reason="Use 'linebot.v3.insight' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AreaInsight(DemographicInsight): - """AreaInsight.""" - - def __init__(self, percentage=None, area=None, **kwargs): - """__init__ method. - - :param float percentage: Percentage. - :param str area: Area - :param kwargs: - """ - super(AreaInsight, self).__init__(percentage=percentage, **kwargs) - - self.area = area - - -@deprecated(reason="Use 'linebot.v3.insight' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AppTypeInsight(DemographicInsight): - """AppTypeInsight.""" - - def __init__(self, percentage=None, app_type=None, **kwargs): - """__init__ method. - - :param float percentage: Percentage. - :param str app_type: OS - :param kwargs: - """ - super(AppTypeInsight, self).__init__(percentage=percentage, **kwargs) - - self.app_type = app_type - - -@deprecated(reason="Use 'linebot.v3.insight' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class SubscriptionPeriodInsight(DemographicInsight): - """SubscriptionPeriodInsight.""" - - def __init__(self, percentage=None, subscription_period=None, **kwargs): - """__init__ method. - - :param float percentage: Percentage. - :param str subscription_period: Friendship duration - :param kwargs: - """ - super(SubscriptionPeriodInsight, self).__init__(percentage=percentage, **kwargs) - - self.subscription_period = subscription_period - - -@deprecated(reason="Use 'linebot.v3.insight' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MessageStatistics(Base): - """MessageStatistics.""" - - def __init__(self, request_id=None, timestamp=None, delivered=None, - unique_impression=None, unique_click=None, unique_media_played=None, - unique_media_played_100_percent=None, **kwargs): - """__init__ method. - - :param str request_id: Request ID. - :param int timestamp: UNIX timestamp for message delivery time. - :param int delivered: Number of messages delivered. This property shows values - of less than 20. - :param int unique_impression: Number of people who opened the message, - meaning they displayed at least 1 bubble. - :param int unique_click: Number of people who opened any URL in the message. - :param int unique_media_played: Number of people who started playing any video - or audio in the message. - :param int unique_media_played_100_percent: Number of people who played the entirety of - any video or audio in the message. - """ - super(MessageStatistics, self).__init__(**kwargs) - - self.request_id = request_id - self.timestamp = timestamp - self.delivered = delivered - self.unique_impression = unique_impression - self.unique_click = unique_click - self.unique_media_played = unique_media_played - self.unique_media_played_100_percent = unique_media_played_100_percent - - -@deprecated(reason="Use 'linebot.v3.insight' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MessageStatisticsOfCustomAggregationUnit(Base): - """MessageStatisticsOfCustomAggregationUnit.""" - - def __init__(self, unique_impression=None, unique_click=None, unique_media_played=None, - unique_media_played_100_percent=None, **kwargs): - """__init__ method. - - :param int unique_impression: Number of people who opened the message, - meaning they displayed at least 1 bubble. - :param int unique_click: Number of people who opened any URL in the message. - :param int unique_media_played: Number of people who started playing any video - or audio in the message. - :param int unique_media_played_100_percent: Number of people who played the entirety of - any video or audio in the message. - """ - super(MessageStatisticsOfCustomAggregationUnit, self).__init__(**kwargs) - - self.unique_impression = unique_impression - self.unique_click = unique_click - self.unique_media_played = unique_media_played - self.unique_media_played_100_percent = unique_media_played_100_percent - - -@deprecated(reason="Use 'linebot.v3.insight' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MessageInsight(Base): - """MessageInsight.""" - - def __init__(self, seq=None, impression=None, media_played=None, - media_played_25_percent=None, media_played_50_percent=None, - media_played_75_percent=None, media_played_100_percent=None, - unique_media_played=None, unique_media_played_25_percent=None, - unique_media_played_50_percent=None, unique_media_played_75_percent=None, - unique_media_played_100_percent=None, **kwargs): - """__init__ method. - - :param int seq: Bubble's serial number. - :param int impression: Number of times the bubble was displayed. - :param int media_played: Number of times audio or video in the bubble started playing. - :param int media_played_25_percent: Number of times audio or video - in the bubble was played from start to 25%. - :param int media_played_50_percent: Number of times audio or video - in the bubble was played from start to 50%. - :param int media_played_75_percent: Number of times audio or video - in the bubble was played from start to 75%. - :param int media_played_100_percent: Number of times audio or video - in the bubble was played in its entirety. - :param int unique_media_played: Number of people that started playing - audio or video in the bubble. - :param int unique_media_played_25_percent: Number of people that played - audio or video in the bubble from start to 25%. - :param int unique_media_played_50_percent: Number of people that played - audio or video in the bubble from start to 50%. - :param int unique_media_played_75_percent: Number of people that played - audio or video in the bubble from start to 75%. - :param int unique_media_played_100_percent: Number of people that played - audio or video in the bubble in its entirety. - """ - super(MessageInsight, self).__init__(**kwargs) - - self.seq = seq - self.impression = impression - self.media_played = media_played - self.media_played_25_percent = media_played_25_percent - self.media_played_50_percent = media_played_50_percent - self.media_played_75_percent = media_played_75_percent - self.media_played_100_percent = media_played_100_percent - self.unique_media_played = unique_media_played - self.unique_media_played_25_percent = unique_media_played_25_percent - self.unique_media_played_50_percent = unique_media_played_50_percent - self.unique_media_played_75_percent = unique_media_played_75_percent - self.unique_media_played_100_percent = unique_media_played_100_percent - - -@deprecated(reason="Use 'linebot.v3.insight' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ClickInsight(Base): - """ClickInsight.""" - - def __init__(self, seq=None, url=None, click=None, unique_click=None, - unique_click_of_request=None, **kwargs): - """__init__ method. - - :param int seq: The URL's serial number. - :param str url: URL. - :param int click: Number of times the URL was opened. - :param int unique_click: Number of people that opened the URL. - :param int unique_click_of_request: Number of people who opened this url - through any link in the message. - """ - super(ClickInsight, self).__init__(**kwargs) - - self.seq = seq - self.url = url - self.click = click - self.unique_click = unique_click - self.unique_click_of_request = unique_click_of_request - - -@deprecated(reason="Use 'linebot.v3.insight' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class JobInsight(Base): - """ClickInsight.""" - - def __init__(self, audience_group_job_id=None, audience_group_id=None, description=None, - type=None, job_status=None, failed_type=None, audience_count=None, - created=None, **kwargs): - """__init__ method. - - :param int audience_group_job_id: A job ID. - :param int audience_group_id: An audience ID. - :param str description: The job's description. - :param str type: The job's type. One of: 'DIFF_ADD' - :param str job_status: The job's status. One of: 'QUEUED', 'WORKING', 'FINISHED', 'FAILED' - :param str failed_type: The reason why the operation failed. This is only included when - jobs[].jobStatus is FAILED. - :param int audience_count: The number of accounts (recipients) that were added or removed. - :param int created: When the job was created (in UNIX time). - :param kwargs: - """ - super(JobInsight, self).__init__(**kwargs) - self.audience_group_job_id = audience_group_job_id - self.audience_group_id = audience_group_id - self.description = description - self.type = type - self.job_status = job_status - self.failed_type = failed_type - self.audience_count = audience_count - self.created = created diff --git a/linebot/models/limit.py b/linebot/models/limit.py deleted file mode 100644 index 3d8acb02a..000000000 --- a/linebot/models/limit.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.recipient module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Limit(with_metaclass(ABCMeta, Base)): - """Limit. - - https://developers.line.biz/en/reference/messaging-api/#send-narrowcast-message - - """ - - def __init__(self, max=None, up_to_remaining_quota=False, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(Limit, self).__init__(**kwargs) - - self.max = max - self.up_to_remaining_quota = up_to_remaining_quota diff --git a/linebot/models/mention.py b/linebot/models/mention.py deleted file mode 100644 index ef74d5fba..000000000 --- a/linebot/models/mention.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.mention module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated - -from linebot.deprecations import ( - LineBotSdkDeprecatedIn30 -) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import Mention' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Mention(with_metaclass(ABCMeta, Base)): - """Mention. - - https://developers.line.biz/en/reference/messaging-api/#text-message - - Object containing the contents of the mentioned user. - """ - - def __init__(self, mentionees=None, **kwargs): - """__init__ method. - - :param List mentionees: Array of LINE mentionee objects - :param kwargs: - """ - super(Mention, self).__init__(**kwargs) - - self.mentionees = mentionees diff --git a/linebot/models/mentionee.py b/linebot/models/mentionee.py deleted file mode 100644 index bae59a069..000000000 --- a/linebot/models/mentionee.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.mentionee module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated - -from linebot.deprecations import ( - LineBotSdkDeprecatedIn30 -) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import Mentionee' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Mentionee(with_metaclass(ABCMeta, Base)): - """Mentionee. - - https://developers.line.biz/en/reference/messaging-api/#text-message - - Mentioned user information. - """ - - def __init__(self, index=None, length=None, user_id=None, **kwargs): - """__init__ method. - - :param int index: Index position of the user mention for a character - :param int length: Length of the text of the mentioned user - :param str user_id: User ID - :param kwargs: - """ - super(Mentionee, self).__init__(**kwargs) - - self.index = index - self.length = length - self.user_id = user_id diff --git a/linebot/models/messages.py b/linebot/models/messages.py deleted file mode 100644 index edc0e5fa8..000000000 --- a/linebot/models/messages.py +++ /dev/null @@ -1,321 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.messages module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from linebot.models.emojis import Emojis -from .mention import Mention -from .mentionee import Mentionee -from .base import Base - -from deprecated import deprecated - -from linebot.deprecations import ( - LineBotSdkDeprecatedIn30 -) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import MessageContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Message(with_metaclass(ABCMeta, Base)): - """Abstract Base Class of Message.""" - - def __init__(self, id=None, use_raw_message=False, **kwargs): - """__init__ method. - - :param str id: Message ID - :param bool use_raw_message: Using original Message key as attribute - :param kwargs: - """ - super(Message, self).__init__(**kwargs) - - if use_raw_message: - self.__dict__.update(kwargs) - - self.type = None - self.id = id - - def __getitem__(self, key): - """__getitem__ method. - - :param str key: Message key - """ - return self.__dict__.get(key, None) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import TextMessageContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class TextMessage(Message): - """TextMessage. - - https://developers.line.biz/en/reference/messaging-api/#wh-text - - Message object which contains the text sent from the source. - """ - - def __init__(self, id=None, text=None, emojis=None, mention=None, **kwargs): - """__init__ method. - - :param str id: Message ID - :param str text: Message text - :param List emojis: Array of LINE emoji objects - :param object mention: LINE mention object - :param kwargs: - """ - super(TextMessage, self).__init__(id=id, **kwargs) - - self.type = 'text' - self.text = text - if emojis: - new_emojis = [] - for emoji in emojis: - emoji_object = self.get_or_new_from_json_dict( - emoji, Emojis - ) - if emoji_object: - new_emojis.append(emoji_object) - self.emojis = new_emojis - else: - self.emojis = emojis - - if mention: - mention_object = self.get_or_new_from_json_dict( - mention, Mention - ) - mentionees = [] - for mentionee in mention_object.mentionees: - mentionee_object = self.get_or_new_from_json_dict( - mentionee, Mentionee - ) - if mentionee_object: - mentionees.append(mentionee_object) - self.mention = Mention(mentionees) - else: - self.mention = mention - - -@deprecated(reason="Use 'from linebot.v3.webhooks import ImageMessageContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ImageMessage(Message): - """ImageMessage. - - https://developers.line.biz/en/reference/messaging-api/#wh-image - - Message object which contains the image content sent from the source. - The binary image data can be retrieved with the Content API. - """ - - def __init__(self, id=None, content_provider=None, image_set=None, **kwargs): - """__init__ method. - - :param str id: Message ID - :param content_provider: ContentProvider object - :type content_provider: - :py:class:`linebot.models.messages.ContentProvider` - :param image_set: ImageSet object - :type image_set: - :py:class:`linebot.models.messages.ImageSet` - :param kwargs: - """ - super(ImageMessage, self).__init__(id=id, **kwargs) - - self.type = 'image' - self.content_provider = self.get_or_new_from_json_dict( - content_provider, ContentProvider - ) - self.image_set = self.get_or_new_from_json_dict( - image_set, ImageSet - ) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import VideoMessageContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class VideoMessage(Message): - """VideoMessage. - - https://developers.line.biz/en/reference/messaging-api/#wh-video - - Message object which contains the video content sent from the source. - The binary video data can be retrieved with the Content API. - """ - - def __init__(self, id=None, duration=None, content_provider=None, **kwargs): - """__init__ method. - - :param str id: Message ID - :param long duration: Length of video file (milliseconds) - :param content_provider: ContentProvider object - :type content_provider: - :py:class:`linebot.models.messages.ContentProvider` - :param kwargs: - """ - super(VideoMessage, self).__init__(id=id, **kwargs) - - self.type = 'video' - self.duration = duration - self.content_provider = self.get_or_new_from_json_dict( - content_provider, ContentProvider - ) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import AudioMessageContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AudioMessage(Message): - """AudioMessage. - - https://developers.line.biz/en/reference/messaging-api/#wh-audio - - Message object which contains the audio content sent from the source. - The binary audio data can be retrieved with the Content API. - """ - - def __init__(self, id=None, duration=None, content_provider=None, **kwargs): - """__init__ method. - - :param str id: Message ID - :param long duration: Length of audio file (milliseconds) - :param content_provider: ContentProvider object - :type content_provider: - :py:class:`linebot.models.messages.ContentProvider` - :param kwargs: - """ - super(AudioMessage, self).__init__(id=id, **kwargs) - - self.type = 'audio' - self.duration = duration - self.content_provider = self.get_or_new_from_json_dict( - content_provider, ContentProvider - ) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import LocationMessageContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class LocationMessage(Message): - """LocationMessage. - - https://developers.line.biz/en/reference/messaging-api/#wh-location - """ - - def __init__(self, id=None, title=None, address=None, latitude=None, longitude=None, - **kwargs): - """__init__ method. - - :param str id: Message ID - :param str title: Title - :param str address: Address - :param float latitude: Latitude - :param float longitude: Longitude - :param kwargs: - """ - super(LocationMessage, self).__init__(id=id, **kwargs) - - self.type = 'location' - self.title = title - self.address = address - self.latitude = latitude - self.longitude = longitude - - -@deprecated(reason="Use 'from linebot.v3.webhooks import StickerMessageContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class StickerMessage(Message): - """StickerMessage. - - https://developers.line.biz/en/reference/messaging-api/#wh-sticker - - Message object which contains the sticker data sent from the source. - For a list of basic LINE stickers and sticker IDs, see sticker list. - """ - - def __init__(self, id=None, package_id=None, sticker_id=None, - sticker_resource_type=None, keywords=None, text=None, **kwargs): - """__init__ method. - - :param str id: Message ID - :param str package_id: Package ID - :param str sticker_id: Sticker ID - :param str sticker_resource_type: Sticker resource type - :param list[str] keywords: List of up to 15 keywords describing the sticker - :param str text: Any text entered by the user - :param kwargs: - """ - super(StickerMessage, self).__init__(id=id, **kwargs) - - self.type = 'sticker' - self.package_id = package_id - self.sticker_id = sticker_id - self.sticker_resource_type = sticker_resource_type - self.keywords = keywords - self.text = text - - -@deprecated(reason="Use 'from linebot.v3.webhooks import FileMessageContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class FileMessage(Message): - """FileMessage. - - https://developers.line.biz/en/reference/messaging-api/#wh-file - - Message object which contains the file content sent from the source. - The binary file data can be retrieved with the Content API. - """ - - def __init__(self, id=None, file_name=None, file_size=None, **kwargs): - """__init__ method. - - :param str id: Message ID - :param str file_name: File Name - :param int file_size: File Size - :param kwargs: - """ - super(FileMessage, self).__init__(id=id, **kwargs) - - self.type = 'file' - self.file_size = file_size - self.file_name = file_name - - -@deprecated(reason="Use 'from linebot.v3.webhooks import ContentProvider' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ContentProvider(Base): - """Content provider.""" - - def __init__(self, type=None, original_content_url=None, preview_image_url=None, **kwargs): - """__init__ method. - - :param str type: Provider of the content. `line` or `external`. - :param str original_content_url: URL of the content. - :param str preview_image_url: URL of the preview image. - :param kwargs: - """ - super(ContentProvider, self).__init__(**kwargs) - - self.type = type - self.original_content_url = original_content_url - self.preview_image_url = preview_image_url - - -@deprecated(reason="Use 'from linebot.v3.webhooks import ImageSet' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ImageSet(Base): - """Image Set.""" - - def __init__(self, id=None, index=None, total=0, **kwargs): - """__init__ method. - - :param str id: Image set ID. - :param int index: Image number in a set of images sent simultaneously. - :param int total: Total number of images sent simultaneously. - :param kwargs: - """ - super(ImageSet, self).__init__(**kwargs) - - self.id = id - self.index = index - self.total = total diff --git a/linebot/models/operator.py b/linebot/models/operator.py deleted file mode 100644 index aee5425e1..000000000 --- a/linebot/models/operator.py +++ /dev/null @@ -1,103 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.filter module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Operator(with_metaclass(ABCMeta, Base)): - """Operator. - - https://developers.line.biz/en/reference/messaging-api/#narrowcast-demographic-filter - - Use logical AND, OR, and NOT operators to combine multiple recipient objects or - demographic filter objects together. - You can specify up to 10 recipient objects or demographic filter objects per request. - """ - - def __init__(self, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(Operator, self).__init__(**kwargs) - - self.type = "operator" - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class And(Operator): - """And. - - Create a new recipient object or demographic filter object by taking the - logical conjunction (AND) of the specified array of objects. - """ - - def __init__(self, *args, **kwargs): - """__init__ method. - - :param args: - :param kwargs: - """ - super(And, self).__init__(**kwargs) - - setattr(self, 'and', args) - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Or(Operator): - """Or. - - Create a new recipient object or demographic filter object by taking the - logical disjunction (OR) of the specified array of objects. - """ - - def __init__(self, *args, **kwargs): - """__init__ method. - - :param args: - :param kwargs: - """ - super(Or, self).__init__(**kwargs) - - setattr(self, 'or', args) - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Not(Operator): - """Not. - - Create a new recipient object or demographic filter object that excludes - in the specified object. - """ - - def __init__(self, arg, **kwargs): - """__init__ method. - - :param arg: - :param kwargs: - """ - super(Not, self).__init__(**kwargs) - - setattr(self, 'not', arg) diff --git a/linebot/models/recipient.py b/linebot/models/recipient.py deleted file mode 100644 index 586c5a955..000000000 --- a/linebot/models/recipient.py +++ /dev/null @@ -1,79 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.limit module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Recipient(with_metaclass(ABCMeta, Base)): - """Recipient. - - https://developers.line.biz/en/reference/messaging-api/#narrowcast-recipient - - Recipient objects represent audiences. You can specify recipients based on - a combination of criteria using logical operator objects. - """ - - def __init__(self, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(Recipient, self).__init__(**kwargs) - - self.type = None - - -@deprecated(reason="Use 'from linebot.v3.messaging import AudienceRecipient' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AudienceRecipient(Recipient): - """AudienceRecipient.""" - - def __init__(self, group_id=None, **kwargs): - """__init__ method. - - :param int group_id: The audience ID. Create audiences with the - Manage Audience API. - :param kwargs: - """ - super(AudienceRecipient, self).__init__(**kwargs) - - self.type = "audience" - self.audience_group_id = group_id - - -@deprecated(reason="Use 'from linebot.v3.messaging import RedeliveryRecipient' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class RedeliveryRecipient(Recipient): - """RedeliveryRecipient.""" - - def __init__(self, request_id=None, **kwargs): - """__init__ method. - - :param str request_id: The request ID of the narrowcast message previously sent. - The request IDs is an ID issued for each Messaging API request. - :param kwargs: - """ - super(RedeliveryRecipient, self).__init__(**kwargs) - - self.type = "redelivery" - self.request_id = request_id diff --git a/linebot/models/responses.py b/linebot/models/responses.py deleted file mode 100644 index 20a355dfc..000000000 --- a/linebot/models/responses.py +++ /dev/null @@ -1,1107 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.responses module.""" - -from .base import Base -from .insight import ( - SubscriptionPeriodInsight, AppTypeInsight, AgeInsight, - GenderInsight, AreaInsight, MessageInsight, ClickInsight, - MessageStatistics, JobInsight, MessageStatisticsOfCustomAggregationUnit, -) -from .rich_menu import RichMenuSize, RichMenuArea, RichMenuAlias - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class BroadcastResponse(object): - """BroadcastResponse. - - https://developers.line.biz/en/reference/messaging-api/#send-broadcast-message - """ - - def __init__(self, request_id=None): - """__init__ method. - - :param str request_id: Request ID. A unique ID is generated for each request - """ - self.request_id = request_id - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ValidateReplyMessageObjectsResponse(object): - """ValidateReplyMessageObjectsResponse. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-reply-message - """ - - def __init__(self, request_id=None): - """__init__ method. - - :param str request_id: Request ID. A unique ID is generated for each request - """ - self.request_id = request_id - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ValidatePushMessageObjectsResponse(object): - """ValidatePushMessageObjectsResponse. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-push-message - """ - - def __init__(self, request_id=None): - """__init__ method. - - :param str request_id: Request ID. A unique ID is generated for each request - """ - self.request_id = request_id - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ValidateMulticastMessageObjectsResponse(object): - """ValidateMulticastMessageObjectsResponse. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-multicast-message - """ - - def __init__(self, request_id=None): - """__init__ method. - - :param str request_id: Request ID. A unique ID is generated for each request - """ - self.request_id = request_id - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ValidateNarrowcastMessageObjectsResponse(object): - """ValidateNarrowcastMessageObjectsResponse. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-narrowcast-message - """ - - def __init__(self, request_id=None): - """__init__ method. - - :param str request_id: Request ID. A unique ID is generated for each request - """ - self.request_id = request_id - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ValidateBroadcastMessageObjectsResponse(object): - """ValidateBroadcastMessageObjectsResponse. - - https://developers.line.biz/en/reference/messaging-api/#validate-message-objects-of-broadcast-message - """ - - def __init__(self, request_id=None): - """__init__ method. - - :param str request_id: Request ID. A unique ID is generated for each request - """ - self.request_id = request_id - - -@deprecated(reason="Use 'from linebot.v3.messaging import UserProfileResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Profile(Base): - """Profile. - - https://developers.line.biz/en/reference/messaging-api/#get-profile - """ - - def __init__(self, display_name=None, user_id=None, picture_url=None, - status_message=None, language=None, **kwargs): - """__init__ method. - - :param str display_name: Display name - :param str user_id: User ID - :param str picture_url: Image URL - :param str status_message: Status message - :param str language: Get user's language - :param kwargs: - """ - super(Profile, self).__init__(**kwargs) - - self.display_name = display_name - self.user_id = user_id - self.picture_url = picture_url - self.status_message = status_message - self.language = language - - -@deprecated(reason="Use 'from linebot.v3.messaging import GroupSummaryResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Group(Base): - """Group. - - https://developers.line.biz/en/reference/messaging-api/#get-group-id-response - """ - - def __init__(self, group_id=None, group_name=None, picture_url=None, **kwargs): - """__init__ method. - - :param str group_id - :param str group_name - :param str picture_url - :param kwargs: - """ - super(Group, self).__init__(**kwargs) - - self.group_id = group_id - self.group_name = group_name - self.picture_url = picture_url - - -@deprecated(reason="Use 'from linebot.v3.messaging import MembersIdsResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MemberIds(Base): - """MemberIds. - - https://developers.line.biz/en/reference/messaging-api/#get-group-member-user-ids - https://developers.line.biz/en/reference/messaging-api/#get-room-member-user-ids - """ - - def __init__(self, member_ids=None, next=None, **kwargs): - """__init__ method. - - :param member_ids: List of user IDs of the members in the group or room. - Max: 100 user IDs - :type member_ids: list[str] - :param str next: continuationToken. - Only returned when there are more user IDs remaining in memberIds. - :param kwargs: - """ - super(MemberIds, self).__init__(**kwargs) - - self.member_ids = member_ids - self.next = next - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Content(object): - """MessageContent. - - https://developers.line.biz/en/reference/messaging-api/#get-content - """ - - def __init__(self, response): - """__init__ method. - - :param response: HttpResponse object - :type response: T <= :py:class:`linebot.http_client.HttpResponse` - """ - self.response = response - - @property - def content_type(self): - """Get Content-type header value. - - :rtype: str - :return: content-type header value - """ - return self.response.headers.get('content-type') - - @property - def content(self): - """Get content. - - If content size is large, should use iter_content. - - :rtype: binary - """ - return self.response.content - - def iter_content(self, chunk_size=1024): - """Get content as iterator (stream). - - If content size is large, should use this. - - :param chunk_size: Chunk size - :rtype: iterator - """ - return self.response.iter_content(chunk_size=chunk_size) - - -@deprecated(reason="Use 'from linebot.v3.messaging import RichMenuResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class RichMenuResponse(Base): - """RichMenuResponse. - - https://developers.line.me/en/docs/messaging-api/reference/#rich-menu-response-object - """ - - def __init__(self, rich_menu_id=None, size=None, selected=None, name=None, - chat_bar_text=None, areas=None, **kwargs): - """__init__ method. - - :param str id: Rich Menu ID - :param size: size object which describe the rich menu displayed in the chat. - Rich menu images must be one of the following sizes: 2500x1686, 2500x843. - :type size: :py:class:`linebot.models.rich_menu.RichMenuSize` - :param bool selected: true to display the rich menu by default. Otherwise, false. - :param str name: Name of the rich menu. - Maximum of 300 characters. - :param str chat_bar_text: Text displayed in the chat bar. - Maximum of 14 characters. - :param areas: Array of area objects which define coordinates and size of tappable areas. - Maximum of 20 area objects. - :type areas: list[T <= :py:class:`linebot.models.rich_menu.RichMenuArea`] - :param kwargs: - """ - super(RichMenuResponse, self).__init__(**kwargs) - - self.rich_menu_id = rich_menu_id - self.size = self.get_or_new_from_json_dict(size, RichMenuSize) - self.selected = selected - self.name = name - self.chat_bar_text = chat_bar_text - - new_areas = [] - if areas: - for area in areas: - new_areas.append( - self.get_or_new_from_json_dict(area, RichMenuArea) - ) - self.areas = new_areas - - -@deprecated(reason="Use 'from linebot.v3.messaging import RichMenuAliasResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class RichMenuAliasResponse(Base): - """RichMenuAliasResponse. - - https://developers.line.biz/en/reference/messaging-api/#get-rich-menu-alias-by-id-response - """ - - def __init__(self, rich_menu_alias_id=None, rich_menu_id=None, **kwargs): - """__init__ method. - - :param str rich_menu_alias_id: Rich menu alias ID. - :param str rich_menu_id: Rich menu ID. - :param kwargs: - """ - super(RichMenuAliasResponse, self).__init__(**kwargs) - - self.rich_menu_alias_id = rich_menu_alias_id - self.rich_menu_id = rich_menu_id - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class RichMenuAliasListResponse(Base): - """RichMenuAliasListResponse. - - https://developers.line.biz/en/reference/messaging-api/#get-rich-menu-alias-list-response - """ - - def __init__(self, aliases=None, **kwargs): - """__init__ method. - - :param aliases: Array of rich menu alias objects - :type areas: list[T <= :py:class:`linebot.models.RichMenuAlias`] - :param kwargs: - """ - super(RichMenuAliasListResponse, self).__init__(**kwargs) - new_aliases = [] - if aliases: - for alias in aliases: - new_aliases.append( - self.get_or_new_from_json_dict(alias, RichMenuAlias) - ) - self.aliases = new_aliases - - -@deprecated(reason="Use 'from linebot.v3.messaging import MessageQuotaResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MessageQuotaResponse(Base): - """MessageQuotaResponse. - - https://developers.line.biz/en/reference/messaging-api/#get-quota - """ - - def __init__(self, type=None, value=None, **kwargs): - """__init__ method. - - :param str type: Quota limitation type - :param int value: The target limit for additional messages in the current month. - This property is returned when the type property has a value of limited. - :param kwargs: - """ - super(MessageQuotaResponse, self).__init__(**kwargs) - - self.type = type - self.value = value - - -@deprecated(reason="Use 'from linebot.v3.messaging import QuotaConsumptionResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MessageQuotaConsumptionResponse(Base): - """MessageQuotaConsumptionResponse. - - https://developers.line.biz/en/reference/messaging-api/#get-consumption - """ - - def __init__(self, total_usage=None, **kwargs): - """__init__ method. - - :param str total_usage: The number of sent messages in the current month - :param kwargs: - """ - super(MessageQuotaConsumptionResponse, self).__init__(**kwargs) - - self.total_usage = total_usage - - -@deprecated(reason="Use 'from linebot.v3.messaging import NumberOfMessagesResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MessageDeliveryBroadcastResponse(Base): - """MessageDeliveryBroadcastResponse.""" - - def __init__(self, status=None, success=None, **kwargs): - """__init__ method. - - :param str status: Status of the counting process. - :param int success: The number of messages sent with the Messaging API on the - date specified in date. - :param kwargs: - """ - super(MessageDeliveryBroadcastResponse, self).__init__(**kwargs) - - self.status = status - self.success = success - - -@deprecated(reason="Use 'from linebot.v3.messaging import NumberOfMessagesResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MessageDeliveryReplyResponse(Base): - """MessageDeliveryReplyResponse.""" - - def __init__(self, status=None, success=None, **kwargs): - """__init__ method. - - :param str status: Status of the counting process. - :param int success: The number of messages sent with the Messaging API on the - date specified in date. - :param kwargs: - """ - super(MessageDeliveryReplyResponse, self).__init__(**kwargs) - - self.status = status - self.success = success - - -@deprecated(reason="Use 'from linebot.v3.messaging import NumberOfMessagesResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MessageDeliveryPushResponse(Base): - """MessageDeliveryPushResponse.""" - - def __init__(self, status=None, success=None, **kwargs): - """__init__ method. - - :param str status: Status of the counting process. - :param int success: The number of messages sent with the Messaging API on the - date specified in date. - :param kwargs: - """ - super(MessageDeliveryPushResponse, self).__init__(**kwargs) - - self.status = status - self.success = success - - -@deprecated(reason="Use 'from linebot.v3.messaging import NumberOfMessagesResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MessageDeliveryMulticastResponse(Base): - """MessageDeliveryMulticastResponse.""" - - def __init__(self, status=None, success=None, **kwargs): - """__init__ method. - - :param str status: Status of the counting process. - :param int success: The number of messages sent with the Messaging API on the - date specified in date. - :param kwargs: - """ - super(MessageDeliveryMulticastResponse, self).__init__(**kwargs) - - self.status = status - self.success = success - - -@deprecated(reason="Use 'from linebot.v3.messaging import NarrowcastProgressResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class MessageProgressNarrowcastResponse(Base): - """MessageProgressNarrowcastResponse.""" - - def __init__(self, phase=None, success_count=None, failure_count=None, - target_count=None, failed_description=None, error_code=None, - accepted_time=None, completed_time=None, **kwargs): - """__init__ method. - - :param str phase: Progress status. One of `waiting`, `sending`, - `succeeded`, or `failed`. - :param int success_count: Number of narrowcast messages sent successful. - :param int failure_count: Number of narrowcast messages sent failed. - :param int target_count: Number of targeted messages sent. - :param str failed_description: Reason why narrowcast failed, useful when - phase is `failed`. - :param int error_code: Summary of the error. One of `1` or `2`. `1` - means internal error, whereas `2` indicates too few targets. - :param str accepted_time: Narrowcast message request accepted time in milliseconds. - :param str completed_time: Processing of narrowcast message request - completion time in milliseconds. - :param kwargs: - """ - super(MessageProgressNarrowcastResponse, self).__init__(**kwargs) - - self.phase = phase - self.success_count = success_count - self.failure_count = failure_count - self.target_count = target_count - self.failed_description = failed_description - self.error_code = error_code - self.accepted_time = accepted_time - self.completed_time = completed_time - - -@deprecated(reason="Use 'from linebot.v3.messaging import IssueLinkTokenResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class IssueLinkTokenResponse(Base): - """IssueLinkTokenResponse. - - https://developers.line.biz/en/reference/messaging-api/#issue-link-token - """ - - def __init__(self, link_token=None, **kwargs): - """__init__ method. - - :param str link_token: Link token. - :param kwargs: - """ - super(IssueLinkTokenResponse, self).__init__(**kwargs) - - self.link_token = link_token - - -@deprecated(reason="Use 'linebot.v3.oauth' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class IssueChannelTokenResponse(Base): - """IssueAccessTokenResponse. - - https://developers.line.biz/en/reference/messaging-api/#issue-channel-access-token - """ - - def __init__(self, access_token=None, expires_in=None, token_type=None, **kwargs): - """__init__ method. - - :param str access_token: Short-lived channel access token. - :param int expires_in: Time until channel access token expires in seconds - from time the token is issued. - :param str token_type: Bearer. - :param kwargs: - """ - super(IssueChannelTokenResponse, self).__init__(**kwargs) - - self.access_token = access_token - self.expires_in = expires_in - self.token_type = token_type - - -@deprecated(reason="Use 'from linebot.v3.insight import GetNumberOfMessageDeliveriesResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class InsightMessageDeliveryResponse(Base): - """InsightMessageDeliveryResponse.""" - - def __init__(self, status=None, broadcast=None, targeting=None, auto_response=None, - welcome_response=None, chat=None, api_broadcast=None, api_push=None, - api_multicast=None, api_reply=None, **kwargs): - """__init__ method. - - :param str status: Calculation status. One of `ready`, `unready`, or `out_of_service`. - :param int broadcast: Number of broadcast messages sent. - :param int targeting: Number of targeted/segmented messages sent. - :param int auto_response: Number of auto-response messages sent. - :param int welcome_response: Number of greeting messages sent. - :param int chat: Number of messages sent from LINE Official Account Manager Chat screen. - :param int api_broadcast: Number of broadcast messages sent with - the Send broadcast message Messaging API operation. - :param int api_push: Number of push messages sent - with the Send push message Messaging API operation. - :param int api_multicast: Number of multicast messages sent with - the Send multicast message Messaging API operation. - :param int api_reply: Number of replies sent - with the Send reply message Messaging API operation. - :param int success: The number of messages sent with the Messaging API - on the date specified in date. - :param kwargs: - """ - super(InsightMessageDeliveryResponse, self).__init__(**kwargs) - - self.status = status - self.broadcast = broadcast - self.targeting = targeting - self.auto_response = auto_response - self.welcome_response = welcome_response - self.chat = chat - self.api_broadcast = api_broadcast - self.api_push = api_push - self.api_multicast = api_multicast - self.api_reply = api_reply - - -@deprecated(reason="Use 'from linebot.v3.insight import GetNumberOfFollowersResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class InsightFollowersResponse(Base): - """InsightFollowersResponse.""" - - def __init__(self, status=None, followers=None, targeted_reaches=None, blocks=None, **kwargs): - """__init__ method. - - :param str status: Calculation status. One of `ready`, `unready`, or `out_of_service`. - :param int followers: The number of times, as of the specified date, - that a user added this LINE official account as a friend for the first time. - :param int targeted_reaches: The number of users, as of the specified date, - that the official account can reach through targeted messages based - on gender, age, and/or region. - :param int blocks: The number of users blocking the account as of the specified date. - :param kwargs: - """ - super(InsightFollowersResponse, self).__init__(**kwargs) - - self.status = status - self.followers = followers - self.targeted_reaches = targeted_reaches - self.blocks = blocks - - -@deprecated(reason="Use 'from linebot.v3.insight import GetFriendsDemographicsResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class InsightDemographicResponse(Base): - """InsightDemographicResponse.""" - - def __init__(self, available=None, genders=None, ages=None, - areas=None, app_types=None, subscription_periods=None, **kwargs): - """__init__ method. - - :param bool available: `true` if friend demographic information is available. - :param genders: Percentage per gender. - :type genders: list[T <= :py:class:`linebot.models.GenderInsight`] - :param ages: Percentage per age group. - :type ages: list[T <= :py:class:`linebot.models.AgeInsight`] - :param areas: Percentage per area. - :type areas: list[T <= :py:class:`linebot.models.AreaInsight`] - :param app_types: Percentage by OS. - :type app_types: list[T <= :py:class:`linebot.models.AppTypeInsight`] - :param subscription_periods: Percentage per friendship duration. - :type subscription_periods: list[T <= :py:class:`linebot.models.SubscriptionPeriodInsight`] - :param kwargs: - """ - super(InsightDemographicResponse, self).__init__(**kwargs) - - self.available = available - self.genders = [self.get_or_new_from_json_dict(it, GenderInsight) for it in genders] - self.ages = [self.get_or_new_from_json_dict(it, AgeInsight) for it in ages] - self.areas = [self.get_or_new_from_json_dict(it, AreaInsight) for it in areas] - self.app_types = [self.get_or_new_from_json_dict(it, AppTypeInsight) for it in app_types] - self.subscription_periods = [self.get_or_new_from_json_dict(it, SubscriptionPeriodInsight) - for it in subscription_periods] - - -@deprecated(reason="Use 'from linebot.v3.insight import GetMessageEventResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class InsightMessageEventResponse(Base): - """InsightMessageEventResponse.""" - - def __init__(self, overview=None, messages=None, clicks=None, **kwargs): - """__init__ method. - - :param overview: Summary of message statistics. - :type overview: T <= :py:class:`linebot.models.MessageStatistics` - :param messages: Array of information about individual message bubbles. - :type messages: list[T <= :py:class:`linebot.models.MessageInsight`] - :param clicks: Array of information about URLs in the message. - :type clicks: list[T <= :py:class:`linebot.models.ClickInsight`] - :param kwargs: - """ - super(InsightMessageEventResponse, self).__init__(**kwargs) - - self.overview = self.get_or_new_from_json_dict(overview, MessageStatistics) - self.messages = [self.get_or_new_from_json_dict(it, MessageInsight) for it in messages] - self.clicks = [self.get_or_new_from_json_dict(it, ClickInsight) for it in clicks] - - -@deprecated(reason="Use 'linebot.v3.insight' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class InsightMessageEventOfCustomAggregationUnitResponse(Base): - """InsightMessageEventResponse.""" - - def __init__(self, overview=None, messages=None, clicks=None, **kwargs): - """__init__ method. - - :param overview: Summary of message statistics. - :type overview: T <= :py:class:`linebot.models.MessageStatisticsOfCustomAggregationUnit` - :param messages: Array of information about individual message bubbles. - :type messages: list[T <= :py:class:`linebot.models.MessageInsight`] - :param clicks: Array of information about URLs in the message. - :type clicks: list[T <= :py:class:`linebot.models.ClickInsight`] - :param kwargs: - """ - super(InsightMessageEventOfCustomAggregationUnitResponse, self).__init__(**kwargs) - - self.overview = self.get_or_new_from_json_dict( - overview, MessageStatisticsOfCustomAggregationUnit) - self.messages = [self.get_or_new_from_json_dict(it, MessageInsight) for it in messages] - self.clicks = [self.get_or_new_from_json_dict(it, ClickInsight) for it in clicks] - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AggregationInfoResponse(Base): - """The number of aggregation units used this month. - - https://developers.line.biz/en/reference/partner-docs/#get-number-of-units-used-this-month - """ - - def __init__(self, num_of_custom_aggregation_units=None, **kwargs): - """__init__ method. - - :param int num_of_custom_aggregation_units: Number of aggregation units used this month. - :param kwargs: - """ - super(AggregationInfoResponse, self).__init__(**kwargs) - - self.num_of_custom_aggregation_units = num_of_custom_aggregation_units - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AggregationNameListResponse(Base): - """The name list of units used this month for statistics aggregation. - - https://developers.line.biz/en/reference/partner-docs/#get-name-list-of-units-used-this-month - """ - - def __init__(self, custom_aggregation_units=None, next=None, **kwargs): - """__init__ method. - - :param custom_aggregation_units: name list of aggregation units used this month. - Max: 100 unit names - :type custom_aggregation_units: list[str] - :param str next: continuationToken. - A continuation token to get the next array of unit names. - :param kwargs: - """ - super(AggregationNameListResponse, self).__init__(**kwargs) - - self.custom_aggregation_units = custom_aggregation_units - self.next = next - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class NarrowcastResponse(Base): - """NarrowcastResponse. - - https://developers.line.biz/en/reference/messaging-api/#send-narrowcast-message - """ - - def __init__(self, request_id=None, **kwargs): - """__init__ method. - - :param str request_id: Request ID. A unique ID is generated for each request - :param kwargs: - """ - super(NarrowcastResponse, self).__init__(**kwargs) - - self.request_id = request_id - - -@deprecated(reason="Use 'from linebot.v3.messaging import BotInfoResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class BotInfo(Base): - """Response of `linebot.get_bot_info()` . - - https://developers.line.biz/en/reference/messaging-api/#get-bot-info - """ - - def __init__(self, user_id=None, basic_id=None, premium_id=None, - display_name=None, picture_url=None, chat_mode=None, - mark_as_read_mode=None, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(BotInfo, self).__init__(**kwargs) - - self.user_id = user_id - self.basic_id = basic_id - self.premium_id = premium_id - self.display_name = display_name - self.picture_url = picture_url - self.chat_mode = chat_mode - self.mark_as_read_mode = mark_as_read_mode - - -@deprecated(reason="Use 'from linebot.v3.messaging import GetWebhookEndpointResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class GetWebhookResponse(Base): - """Response of `get_webhook_endpoint()` . - - https://developers.line.biz/en/reference/messaging-api/#get-webhook-endpoint-information - """ - - def __init__(self, endpoint=None, active=None, **kwargs): - """__init__ method. - - :param str endpoint: The webhook endpoint URL. - :param bool active: Whether the webhook is in use. - :param kwargs: - """ - super(GetWebhookResponse, self).__init__(**kwargs) - - self.endpoint = endpoint - self.active = active - - -@deprecated(reason="Use 'from linebot.v3.messaging import TestWebhookEndpointResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class TestWebhookResponse(Base): - """Response of `test_webhook_endpoint()` . - - https://developers.line.biz/en/reference/messaging-api/#test-webhook-endpoint - """ - - def __init__(self, success=None, timestamp=None, status_code=None, - reason=None, detail=None, **kwargs): - """__init__ method. - - :param bool success: Result of the communication from the LINE platform - to the webhook URL. - :param str timestamp: Timestamp - :param int status_code: The HTTP status code. - :param str reason: Reason for the response. - :param str detail: Details of the response. - :param kwargs: - """ - super(TestWebhookResponse, self).__init__(**kwargs) - - self.success = success - self.timestamp = timestamp - self.status_code = status_code - self.reason = reason - self.detail = detail - - -@deprecated(reason="Use 'linebot.v3.audience' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AudienceGroup(Base): - """AudienceGroups. - - https://developers.line.biz/en/reference/messaging-api/#get-audience-group - """ - - def __init__(self, audience_group_id=None, type=None, description=None, status=None, - audience_count=None, created=None, is_ifa_audience=None, permission=None, - create_route=None, request_id=None, failed_type=None, click_url=None, - jobs=None, **kwargs): - """__init__ method. - - :param int audience_group_id: The audience ID. - :param str type: The audience type. One of `UPLOAD` or `CLICK` or `IMP` or `CHAT_TAG` - or `FRIEND_PATH`. - :param str description: The audience's name. - :param str status: The audience's status. One of `IN_PROGRESS` or `READY` or `FAILED` - or `EXPIRED`. - :param int audience_count: The number of valid recipients. - :param int created: When the audience was created (in UNIX time). - :param bool is_ifa_audience: The value specified when creating an audience for uploading - user IDs to indicate the type of accounts that will be given as recipients. - :param str permission: Audience's update permission. Audiences linked to the same channel - will be READ_WRITE. - :param str create_route: How the audience was created. If omitted, - you will get all audiences. - :param str request_id: The request ID that was specified when the audience was created. - :param str failed_type: The reason why the operation failed. This is only included when - status is FAILED. One of `AUDIENCE_GROUP_AUDIENCE_INSUFFICIENT` or `INTERNAL_ERROR` - :param str click_url: The URL that was specified when the audience was created. - This is only included when type is CLICK - :param jobs: An array of jobs. This array is used to keep track of each attempt to - add new user IDs or IFAs to an audience for uploading user IDs. - :param kwargs: - """ - super(AudienceGroup, self).__init__(**kwargs) - - self.audience_group_id = audience_group_id - self.type = type - self.description = description - self.status = status - self.audience_count = audience_count - self.created = created - self.is_ifa_audience = is_ifa_audience - self.permission = permission - self.create_route = create_route - self.request_id = request_id - self.failed_type = failed_type - self.click_url = click_url - if jobs: - self.jobs = [self.get_or_new_from_json_dict(job, JobInsight) for job in jobs] - - -@deprecated(reason="Use 'linebot.v3.audience' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ClickAudienceGroup(Base): - """ClickAudienceGroup. - - https://developers.line.biz/en/reference/messaging-api/#create-click-audience-group - """ - - def __init__(self, audience_group_id=None, create_route=None, type=None, description=None, - created=None, permission=None, expire_timestamp=None, is_ifa_audience=None, - request_id=None, click_url=None, **kwargs): - """__init__ method. - - :param int audience_group_id: The audience ID. - :param str create_route: How the audience was created. If omitted, - you will get all audiences. - :param str type: The audience type. One of `UPLOAD` or `CLICK` or `IMP` or `CHAT_TAG` - or `FRIEND_PATH`. - :param str description: The audience's name. - :param int created: When the audience was created (in UNIX time). - :param str permission: Audience's update permission. Audiences linked to the same channel - will be READ_WRITE. - :param int expire_timestamp: Time of audience expiration. Only returned for specific - audiences. - :param bool is_ifa_audience: The value specified when creating an audience for uploading - user IDs to indicate the type of accounts that will be given as recipients. - :param str request_id: The request ID that was specified when the audience was created. - :param str click_url: The URL that was specified when the audience was created. - This is only included when type is CLICK - :param kwargs: - """ - super(ClickAudienceGroup, self).__init__(**kwargs) - - self.audience_group_id = audience_group_id - self.create_route = create_route - self.type = type - self.description = description - self.created = created - self.permission = permission - self.expire_timestamp = expire_timestamp - self.is_ifa_audience = is_ifa_audience - self.request_id = request_id - self.click_url = click_url - - -@deprecated(reason="Use 'linebot.v3.audience' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class CreateAudienceGroup(Base): - """ClickAudienceGroup. - - https://developers.line.biz/en/reference/messaging-api/#create-upload-audience-group - """ - - def __init__(self, audience_group_id=None, create_route=None, type=None, description=None, - created=None, permission=None, expire_timestamp=None, is_ifa_audience=None, - **kwargs): - """__init__ method. - - :param int audience_group_id: The audience ID. - :param str create_route: How the audience was created. If omitted, - you will get all audiences. - :param str type: The audience type. One of `UPLOAD` or `CLICK` or `IMP` or `CHAT_TAG` - or `FRIEND_PATH`. - :param str description: The audience's name. - :param int created: When the audience was created (in UNIX time). - :param str permission: Audience's update permission. Audiences linked to the same channel - will be READ_WRITE. - :param int expire_timestamp: Time of audience expiration. Only returned for specific - audiences. - :param bool is_ifa_audience: The value specified when creating an audience for uploading - user IDs to indicate the type of accounts that will be given as recipients. - :param kwargs: - """ - super(CreateAudienceGroup, self).__init__(**kwargs) - - self.audience_group_id = audience_group_id - self.create_route = create_route - self.type = type - self.description = description - self.created = created - self.permission = permission - self.expire_timestamp = expire_timestamp - self.is_ifa_audience = is_ifa_audience - - -@deprecated(reason="Use 'linebot.v3.audience' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ImpAudienceGroup(Base): - """ImpAudienceGroup. - - https://developers.line.biz/en/reference/messaging-api/#create-imp-audience-group - """ - - def __init__(self, audience_group_id=None, create_route=None, type=None, description=None, - created=None, permission=None, expire_timestamp=None, is_ifa_audience=None, - request_id=None, **kwargs): - """__init__ method. - - :param int audience_group_id: The audience ID. - :param str create_route: How the audience was created. If omitted, - you will get all audiences. - :param str type: The audience type. One of `UPLOAD` or `CLICK` or `IMP` or `CHAT_TAG` - or `FRIEND_PATH`. - :param str description: The audience's name. - :param int created: When the audience was created (in UNIX time). - :param str permission: Audience's update permission. Audiences linked to the same channel - will be READ_WRITE. - :param int expire_timestamp: Time of audience expiration. Only returned for specific - audiences. - :param bool is_ifa_audience: The value specified when creating an audience for uploading - user IDs to indicate the type of accounts that will be given as recipients. - :param str request_id: The request ID that was specified when the audience was created. - :param kwargs: - """ - super(ImpAudienceGroup, self).__init__(**kwargs) - - self.audience_group_id = audience_group_id - self.create_route = create_route - self.type = type - self.description = description - self.created = created - self.permission = permission - self.expire_timestamp = expire_timestamp - self.is_ifa_audience = is_ifa_audience - self.request_id = request_id - - -@deprecated(reason="Use 'linebot.v3.audience' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class GetAuthorityLevel(Base): - """GetAuthorityLevel. - - https://developers.line.biz/en/reference/messaging-api/#get-authority-level - """ - - def __init__(self, authority_level=None, **kwargs): - """__init__ method. - - :param str authority_level: The authority level for all audiences linked to a channel. - :param kwargs: - """ - super(GetAuthorityLevel, self).__init__(**kwargs) - - self.authority_level = authority_level - - -@deprecated(reason="Use 'linebot.v3.audience' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Audience(Base): - """Audience. - - https://developers.line.biz/en/reference/messaging-api/#update-upload-audience-group - """ - - def __init__(self, id=None, **kwargs): - """__init__ method. - - :param str audience_id: A user ID or IFA. - :param kwargs: - """ - super(Audience, self).__init__(**kwargs) - self.id = id - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class UserIds(Base): - """UserIds. - - https://developers.line.biz/en/reference/messaging-api/#get-follower-ids - """ - - def __init__(self, user_ids=None, next=None, **kwargs): - """__init__ method. - - :param user_ids: List of user IDs of users - that have added the LINE Official Account as a friend. - Max: 300 user IDs - :type user_ids: list[str] - :param str next: continuationToken. - A continuation token to get the next array of user IDs. - :param kwargs: - """ - super(UserIds, self).__init__(**kwargs) - - self.user_ids = user_ids - self.next = next - - -@deprecated(reason="Use 'linebot.v3.oauth' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class IssueChannelTokenResponseV2(Base): - """IssueAccessTokenResponseV2. - - https://developers.line.biz/en/reference/messaging-api/#issue-channel-access-token-v2-1 - """ - - def __init__(self, access_token=None, expires_in=None, token_type=None, key_id=None, **kwargs): - """__init__ method. - - :param str access_token: Short-lived channel access token. - :param int expires_in: Time until channel access token expires in seconds - from time the token is issued. - :param str token_type: Bearer. - :param key_id: Unique key ID for identifying the channel access token. - :param kwargs: - """ - super(IssueChannelTokenResponseV2, self).__init__(**kwargs) - - self.access_token = access_token - self.expires_in = expires_in - self.token_type = token_type - self.key_id = key_id - - -@deprecated(reason="Use 'linebot.v3.oauth' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ChannelAccessTokens(Base): - """ChannelAccessTokens. - - https://developers.line.biz/en/reference/messaging-api/#get-issued-channel-access-tokens-v2-1 - """ - - def __init__(self, access_tokens=None, **kwargs): - """__init__ method. - - :param access_tokens: List of channel access token - :type access_tokens: list[str] - :param kwargs: - - """ - super(ChannelAccessTokens, self).__init__(**kwargs) - - self.access_tokens = access_tokens - - -@deprecated(reason="Use 'linebot.v3.oauth' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class VerifyChannelTokenResponseV2(Base): - """VerifyChannelTokenResponseV2. - - https://developers.line.biz/en/reference/messaging-api/#verfiy-channel-access-token-v2-1 - - """ - - def __init__(self, client_id=None, expires_in=None, scope=None, **kwargs): - """__init__ method. - - :param str client_id: The channel ID for which the channel access token was issued. - :param int expires_in: Number of seconds before the channel access token expires. - :param str scope: Permissions granted to the channel access token. - :param kwargs: - - """ - super(VerifyChannelTokenResponseV2, self).__init__(**kwargs) - - self.client_id = client_id - self.expires_in = expires_in - self.scope = scope - - -@deprecated(reason="Use 'linebot.v3.oauth' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ValidAccessTokenKeyIDsResponse(Base): - """ValidAccessTokenKeyIDsResponse. - - https://developers.line.biz/en/reference/messaging-api/#get-all-valid-channel-access-token-key-ids-v2-1 - - """ - - def __init__(self, kids=None, **kwargs): - """__init__ method. - - :param kids: Array of channel access token key IDs. - :type kids: list[str] - :param kwargs: - """ - super(ValidAccessTokenKeyIDsResponse, self).__init__(**kwargs) - - self.kids = kids diff --git a/linebot/models/rich_menu.py b/linebot/models/rich_menu.py deleted file mode 100644 index a3d606dd7..000000000 --- a/linebot/models/rich_menu.py +++ /dev/null @@ -1,153 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.rich_menu module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .actions import get_action -from .base import Base - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'from linebot.v3.messaging import RichMenuRequest' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class RichMenu(with_metaclass(ABCMeta, Base)): - """RichMenu. - - https://developers.line.me/en/docs/messaging-api/reference/#rich-menu-object - """ - - def __init__(self, size=None, selected=None, name=None, chat_bar_text=None, - areas=None, **kwargs): - """__init__ method. - - :param size: size object which describe the rich menu displayed in the chat. - Rich menu images must be one of the following sizes: 2500x1686, 2500x843. - :type size: :py:class:`linebot.models.rich_menu.RichMenuSize` - :param bool selected: true to display the rich menu by default. Otherwise, false. - :param str name: Name of the rich menu. - Maximum of 300 characters. - :param str chatBarText: Text displayed in the chat bar. - Maximum of 14 characters. - :param areas: Array of area objects which define coordinates and size of tappable areas. - Maximum of 20 area objects. - :type areas: list[T <= :py:class:`linebot.models.rich_menu.RichMenuArea`] - :param kwargs: - """ - super(RichMenu, self).__init__(**kwargs) - - self.size = self.get_or_new_from_json_dict(size, RichMenuSize) - self.selected = selected - self.name = name - self.chat_bar_text = chat_bar_text - - new_areas = [] - if areas: - for area in areas: - new_areas.append( - self.get_or_new_from_json_dict(area, RichMenuArea) - ) - self.areas = new_areas - - -@deprecated(reason="Use 'from linebot.v3.messaging import RichMenuSize' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class RichMenuSize(with_metaclass(ABCMeta, Base)): - """RichMenuSize. - - https://developers.line.me/en/docs/messaging-api/reference/#size-object - """ - - def __init__(self, width=None, height=None, **kwargs): - """__init__ method. - - :param int width: Width of the rich menu. Must be 2500. - :param int height: Height of the rich menu. Possible values: 1686, 843. - :param kwargs: - """ - super(RichMenuSize, self).__init__(**kwargs) - - self.width = width - self.height = height - - -@deprecated(reason="Use 'from linebot.v3.messaging import RichMenuArea' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class RichMenuArea(with_metaclass(ABCMeta, Base)): - """RichMenuArea. - - https://developers.line.me/en/docs/messaging-api/reference/#area-object - """ - - def __init__(self, bounds=None, action=None, **kwargs): - """__init__ method. - - :param bounds: Object describing the boundaries of the area in pixels. See bounds object. - :type bounds: :py:class:`linebot.models.rich_menu.RichMenuBound` - :param action: Action performed when the area is tapped. See action objects. - :type action: T <= :py:class:`linebot.models.actions.Action` - :param kwargs: - """ - super(RichMenuArea, self).__init__(**kwargs) - - self.bounds = self.get_or_new_from_json_dict(bounds, RichMenuBounds) - self.action = get_action(action) - - -@deprecated(reason="Use 'from linebot.v3.messaging import RichMenuBounds' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class RichMenuBounds(with_metaclass(ABCMeta, Base)): - """RichMenuBounds. - - https://developers.line.me/en/docs/messaging-api/reference/#bounds-object - """ - - def __init__(self, x=None, y=None, width=None, height=None, **kwargs): - """__init__ method. - - :param int x: Horizontal position relative to the top-left corner of the area. - :param int y: Vertical position relative to the top-left corner of the area. - :param int width: Width of the area. - :param int height: Height of the area. - :param kwargs: - """ - super(RichMenuBounds, self).__init__(**kwargs) - - self.x = x - self.y = y - self.width = width - self.height = height - - -@deprecated(reason="Use 'from linebot.v3.messaging import RichMenuAliasResponse' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class RichMenuAlias(with_metaclass(ABCMeta, Base)): - """RichMenuAlias. - - https://developers.line.biz/en/reference/messaging-api/#create-rich-menu-alias - """ - - def __init__(self, rich_menu_alias_id=None, rich_menu_id=None, **kwargs): - """__init__ method. - - :param string rich_menu_alias_id: Rich menu alias ID, - which can be any ID, unique for each channel. - :param string rich_menu_id: The rich menu ID to be associated with the rich menu alias. - :param kwargs: - """ - super(RichMenuAlias, self).__init__(**kwargs) - - self.rich_menu_alias_id = rich_menu_alias_id - self.rich_menu_id = rich_menu_id diff --git a/linebot/models/send_messages.py b/linebot/models/send_messages.py deleted file mode 100644 index bead1d204..000000000 --- a/linebot/models/send_messages.py +++ /dev/null @@ -1,290 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.send_messages module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .emojis import Emojis -from .actions import get_action -from .base import Base - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class SendMessage(with_metaclass(ABCMeta, Base)): - """Abstract Base Class of SendMessage.""" - - def __init__(self, quick_reply=None, sender=None, **kwargs): - """__init__ method. - - :param quick_reply: QuickReply object - :type quick_reply: T <= :py:class:`linebot.models.send_messages.QuickReply` - :param sender: Sender object - :type sender: T <= :py:class:`linebot.models.send_messages.Sender` - :param kwargs: - """ - super(SendMessage, self).__init__(**kwargs) - - self.type = None - self.quick_reply = self.get_or_new_from_json_dict(quick_reply, QuickReply) - self.sender = self.get_or_new_from_json_dict(sender, Sender) - - -@deprecated(reason="Use 'from linebot.v3.messaging import TextMessage' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class TextSendMessage(SendMessage): - """TextSendMessage. - - https://developers.line.biz/en/reference/messaging-api/#text-message - """ - - def __init__(self, text=None, emojis=None, quick_reply=None, sender=None, **kwargs): - """__init__ method. - - :param str text: Message text - :param quick_reply: QuickReply object - :type quick_reply: T <= :py:class:`linebot.models.send_messages.QuickReply` - :type sender: T <= :py:class:`linebot.models.send_messages.Sender` - :param kwargs: - """ - super(TextSendMessage, self).__init__(quick_reply=quick_reply, sender=sender, **kwargs) - - self.type = 'text' - self.text = text - if emojis: - new_emojis = [] - for emoji in emojis: - emoji_object = self.get_or_new_from_json_dict( - emoji, Emojis - ) - if emoji_object: - new_emojis.append(emoji_object) - self.emojis = new_emojis - else: - self.emojis = emojis - - -@deprecated(reason="Use 'from linebot.v3.messaging import ImageMessage' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ImageSendMessage(SendMessage): - """ImageSendMessage. - - https://developers.line.biz/en/reference/messaging-api/#image-message - """ - - def __init__(self, original_content_url=None, preview_image_url=None, - quick_reply=None, sender=None, **kwargs): - """__init__ method. - - :param str original_content_url: Image URL. - HTTPS - JPEG - Max: 1024 x 1024 - Max: 1 MB - :param str preview_image_url: Preview image URL - HTTPS - JPEG - Max: 240 x 240 - Max: 1 MB - :param quick_reply: QuickReply object - :type quick_reply: T <= :py:class:`linebot.models.send_messages.QuickReply` - :type sender: T <= :py:class:`linebot.models.send_messages.Sender` - :param kwargs: - """ - super(ImageSendMessage, self).__init__(quick_reply=quick_reply, sender=sender, **kwargs) - - self.type = 'image' - self.original_content_url = original_content_url - self.preview_image_url = preview_image_url - - -@deprecated(reason="Use 'from linebot.v3.messaging import VideoMessage' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class VideoSendMessage(SendMessage): - """VideoSendMessage. - - https://developers.line.biz/en/reference/messaging-api/#video-message - """ - - def __init__(self, original_content_url=None, preview_image_url=None, - tracking_id=None, quick_reply=None, sender=None, **kwargs): - """__init__ method. - - :param str original_content_url: URL of video file. - HTTPS. mp4. Less than 1 minute. Max: 10 MB. - :param str preview_image_url: URL of preview image. - HTTPS. JPEG. Max: 240 x 240. Max: 1 MB. - :param str tracking_id: the video viewing complete event occurs - when the user finishes watching the video. - Max character limit: 100. - :param quick_reply: QuickReply object - :type quick_reply: T <= :py:class:`linebot.models.send_messages.QuickReply` - :type sender: T <= :py:class:`linebot.models.send_messages.Sender` - :param kwargs: - """ - super(VideoSendMessage, self).__init__(quick_reply=quick_reply, sender=sender, **kwargs) - - self.type = 'video' - self.original_content_url = original_content_url - self.preview_image_url = preview_image_url - self.tracking_id = tracking_id - - -@deprecated(reason="Use 'from linebot.v3.messaging import AudioMessage' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class AudioSendMessage(SendMessage): - """AudioSendMessage. - - https://developers.line.biz/en/reference/messaging-api/#audio-message - """ - - def __init__(self, original_content_url=None, duration=None, quick_reply=None, - sender=None, **kwargs): - """__init__ method. - - :param str original_content_url: URL of audio file. HTTPS. - m4a. Less than 1 minute. Max 10 MB. - :param long duration: Length of audio file (milliseconds). - :param quick_reply: QuickReply object - :type quick_reply: T <= :py:class:`linebot.models.send_messages.QuickReply` - :type sender: T <= :py:class:`linebot.models.send_messages.Sender` - :param kwargs: - """ - super(AudioSendMessage, self).__init__(quick_reply=quick_reply, sender=sender, **kwargs) - - self.type = 'audio' - self.original_content_url = original_content_url - self.duration = duration - - -@deprecated(reason="Use 'from linebot.v3.messaging import LocationMessage' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class LocationSendMessage(SendMessage): - """LocationSendMessage. - - https://developers.line.biz/en/reference/messaging-api/#location-message - """ - - def __init__(self, title=None, address=None, latitude=None, longitude=None, - quick_reply=None, sender=None, **kwargs): - """__init__ method. - - :param str title: Title - :param str address: Address - :param float latitude: Latitude - :param float longitude: Longitude - :param quick_reply: QuickReply object - :type quick_reply: T <= :py:class:`linebot.models.send_messages.QuickReply` - :type sender: T <= :py:class:`linebot.models.send_messages.Sender` - :param kwargs: - """ - super(LocationSendMessage, self).__init__(quick_reply=quick_reply, sender=sender, **kwargs) - - self.type = 'location' - self.title = title - self.address = address - self.latitude = latitude - self.longitude = longitude - - -@deprecated(reason="Use 'from linebot.v3.messaging import StickerMessage' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class StickerSendMessage(SendMessage): - """StickerSendMessage. - - https://developers.line.biz/en/reference/messaging-api/#sticker-message - """ - - def __init__(self, package_id=None, sticker_id=None, quick_reply=None, sender=None, **kwargs): - """__init__ method. - - :param str package_id: Package ID - :param str sticker_id: Sticker ID - :param quick_reply: QuickReply object - :type quick_reply: T <= :py:class:`linebot.models.send_messages.QuickReply` - :type sender: T <= :py:class:`linebot.models.send_messages.Sender` - :param kwargs: - """ - super(StickerSendMessage, self).__init__(quick_reply=quick_reply, sender=sender, **kwargs) - - self.type = 'sticker' - self.package_id = package_id - self.sticker_id = sticker_id - - -@deprecated(reason="Use 'from linebot.v3.messaging import QuickReply' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class QuickReply(with_metaclass(ABCMeta, Base)): - """QuickReply. - - https://developers.line.me/en/docs/messaging-api/#quick-reply - """ - - def __init__(self, items=None, **kwargs): - """__init__ method. - - :param items: Quick reply button objects - :type items: list[T <= :py:class:`linebot.models.send_messages.QuickReplyButton`] - :param kwargs: - """ - super(QuickReply, self).__init__(**kwargs) - - new_items = [] - if items: - for item in items: - new_items.append(self.get_or_new_from_json_dict( - item, QuickReplyButton - )) - self.items = new_items - - -@deprecated(reason="Use 'from linebot.v3.messaging import QuickReplyItem' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class QuickReplyButton(with_metaclass(ABCMeta, Base)): - """QuickReplyButton. - - https://developers.line.me/en/reference/messaging-api/#quick-reply-button-object - """ - - def __init__(self, image_url=None, action=None, **kwargs): - """__init__ method. - - :param str image_url: URL of the icon that is displayed - at the beginning of the button - :param action: Action performed when this button is tapped - :type action: T <= :py:class:`linebot.models.actions.Action` - :param kwargs: - """ - super(QuickReplyButton, self).__init__(**kwargs) - - self.type = 'action' - self.image_url = image_url - self.action = get_action(action) - - -@deprecated(reason="Use 'from linebot.v3.messaging import Sender' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Sender(with_metaclass(ABCMeta, Base)): - """Sender. - - https://developers.line.biz/en/reference/messaging-api/#icon-nickname-switch - """ - - def __init__(self, name=None, icon_url=None, **kwargs): - """__init__ method. - - :param str name: Display name - :param str icon_url: Icon image URL - """ - super(Sender, self).__init__(**kwargs) - - self.name = name - self.icon_url = icon_url diff --git a/linebot/models/sources.py b/linebot/models/sources.py deleted file mode 100644 index e1073b099..000000000 --- a/linebot/models/sources.py +++ /dev/null @@ -1,157 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.sources module.""" - - -import warnings -from abc import ABCMeta, abstractproperty - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated - -from linebot.deprecations import ( - LineBotSdkDeprecatedIn30 -) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import Source' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Source(with_metaclass(ABCMeta, Base)): - """Abstract Base Class of Source.""" - - def __init__(self, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(Source, self).__init__(**kwargs) - self.type = None - - @abstractproperty - def sender_id(self): - """Abstract property of id to send a message. - - If SourceUser, return user_id. - If SourceGroup, return group_id. - If SourceRoom, return room_id. - - 'sender_id' is deprecated. - - :rtype: str - """ - warnings.warn("'sender_id' is deprecated.", DeprecationWarning, stacklevel=2) - raise NotImplementedError - - -@deprecated(reason="Use 'from linebot.v3.webhooks import UserSource' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class SourceUser(Source): - """SourceUser. - - https://developers.line.biz/en/reference/messaging-api/#source-user - - JSON object which contains the source user of the event. - """ - - def __init__(self, user_id=None, **kwargs): - """__init__ method. - - :param str user_id: ID of the source user - :param kwargs: - """ - super(SourceUser, self).__init__(**kwargs) - - self.type = 'user' - self.user_id = user_id - - @property - def sender_id(self): - """Alias of user_id. - - 'sender_id' is deprecated. Use 'user_id' instead. - - :rtype: str - """ - warnings.warn("'sender_id' is deprecated.", DeprecationWarning, stacklevel=2) - return self.user_id - - -@deprecated(reason="Use 'from linebot.v3.webhooks import GroupSource' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class SourceGroup(Source): - """SourceGroup. - - https://developers.line.biz/en/reference/messaging-api/#source-group - - JSON object which contains the source group of the event. - """ - - def __init__(self, group_id=None, user_id=None, **kwargs): - """__init__ method. - - :param str group_id: ID of the source group - :param str user_id: ID of the source user - :param kwargs: - """ - super(SourceGroup, self).__init__(**kwargs) - - self.type = 'group' - self.group_id = group_id - self.user_id = user_id - - @property - def sender_id(self): - """Alias of group_id. - - 'sender_id' is deprecated. Use 'group_id' instead. - - :rtype: str - """ - warnings.warn("'sender_id' is deprecated.", DeprecationWarning, stacklevel=2) - return self.group_id - - -@deprecated(reason="Use 'from linebot.v3.webhooks import RoomSource' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class SourceRoom(Source): - """SourceRoom. - - https://developers.line.biz/en/reference/messaging-api/#source-room - - JSON object which contains the source room of the event. - """ - - def __init__(self, room_id=None, user_id=None, **kwargs): - """__init__ method. - - :param str room_id: ID of the source room - :param str user_id: ID of the source user - :param kwargs: - """ - super(SourceRoom, self).__init__(**kwargs) - - self.type = 'room' - self.room_id = room_id - self.user_id = user_id - - @property - def sender_id(self): - """Alias of room_id. - - 'sender_id' is deprecated. Use 'room_id' instead. - - :rtype: str - """ - warnings.warn("'sender_id' is deprecated.", DeprecationWarning, stacklevel=2) - return self.room_id diff --git a/linebot/models/template.py b/linebot/models/template.py deleted file mode 100644 index 19b89eb77..000000000 --- a/linebot/models/template.py +++ /dev/null @@ -1,281 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.template module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .actions import get_action, get_actions -from .base import Base -from .send_messages import SendMessage - -from deprecated import deprecated -from linebot.deprecations import LineBotSdkDeprecatedIn30 - - -@deprecated(reason="Use 'from linebot.v3.messaging import TemplateMessage' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class TemplateSendMessage(SendMessage): - """TemplateSendMessage. - - https://developers.line.biz/en/reference/messaging-api/#template-messages - - Template messages are messages with predefined layouts which you can customize. - There are three types of templates available - that can be used to interact with users through your bot. - """ - - def __init__(self, alt_text=None, template=None, **kwargs): - """__init__ method. - - :param str alt_text: Alternative text for unsupported devices. - :param template: Object with the contents of the template. - :type template: T <= :py:class:`linebot.models.template.Template` - :param kwargs: - """ - super(TemplateSendMessage, self).__init__(**kwargs) - - self.type = 'template' - self.alt_text = alt_text - self.template = self.get_or_new_from_json_dict_with_types( - template, { - 'buttons': ButtonsTemplate, - 'confirm': ConfirmTemplate, - 'carousel': CarouselTemplate, - 'image_carousel': ImageCarouselTemplate - } - ) - - -@deprecated(reason="Use 'linebot.v3.messaging' module instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Template(with_metaclass(ABCMeta, Base)): - """Abstract Base Class of Template.""" - - def __init__(self, **kwargs): - """__init__ method. - - :param kwargs: - """ - super(Template, self).__init__(**kwargs) - - self.type = None - - -@deprecated(reason="Use 'from linebot.v3.messaging import ButtonsTemplate' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ButtonsTemplate(Template): - """ButtonsTemplate. - - https://developers.line.biz/en/reference/messaging-api/#buttons - - Template message with an image, title, text, and multiple action buttons. - """ - - def __init__(self, text=None, title=None, thumbnail_image_url=None, - image_aspect_ratio=None, - image_size=None, image_background_color=None, - actions=None, default_action=None, **kwargs): - """__init__ method. - - :param str text: Message text. - Max: 160 characters (no image or title). - Max: 60 characters (message with an image or title) - :param str title: Title. - Max: 40 characters - :param str thumbnail_image_url: Image URL. - HTTPS - JPEG or PNG - Aspect ratio: 1:1.51 - Max width: 1024px - Max: 1 MB - :param str image_aspect_ratio: Aspect ratio of the image. - Specify one of the following values: - rectangle: 1.51:1 - square: 1:1 - :param str image_size: Size of the image. Specify ``cover`` or ``contain``. - :param str image_background_color: Background color of image. - Specify a RGB color value. - :param actions: Action when tapped. - Max: 4 - :type actions: list[T <= :py:class:`linebot.models.actions.Action`] - :param default_action: Action when image is tapped; - set for the entire image, title, and text area - :type default_action: T <= :py:class:`linebot.models.actions.Action` - :param kwargs: - """ - super(ButtonsTemplate, self).__init__(**kwargs) - - self.type = 'buttons' - self.text = text - self.title = title - self.thumbnail_image_url = thumbnail_image_url - self.image_aspect_ratio = image_aspect_ratio - self.image_size = image_size - self.image_background_color = image_background_color - self.actions = get_actions(actions) - self.default_action = get_action(default_action) - - -@deprecated(reason="Use 'from linebot.v3.messaging import ConfirmTemplate' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ConfirmTemplate(Template): - """ConfirmTemplate. - - https://developers.line.biz/en/reference/messaging-api/#confirm - - Template message with two action buttons. - """ - - def __init__(self, text=None, actions=None, **kwargs): - """__init__ method. - - :param str text: Message text. - Max: 240 characters - :param actions: Action when tapped. - Max: 2 - :type actions: list[T <= :py:class:`linebot.models.actions.Action`] - :param kwargs: - """ - super(ConfirmTemplate, self).__init__(**kwargs) - - self.type = 'confirm' - self.text = text - self.actions = get_actions(actions) - - -@deprecated(reason="Use 'from linebot.v3.messaging import CarouselTemplate' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class CarouselTemplate(Template): - """CarouselTemplate. - - https://developers.line.biz/en/reference/messaging-api/#carousel - - Template message with multiple columns which can be cycled like a carousel. - """ - - def __init__(self, columns=None, image_aspect_ratio=None, - image_size=None, **kwargs): - """__init__ method. - - :param columns: Array of columns. - Max: 10 - :type columns: list[T <= :py:class:`linebot.models.template.CarouselColumn`] - :param str image_aspect_ratio: Aspect ratio of the image. - Specify ``rectangle`` or ``square``. - :param str image_size: Size of the image. Specify ``cover`` or ``contain``. - :param kwargs: - """ - super(CarouselTemplate, self).__init__(**kwargs) - - self.type = 'carousel' - - new_columns = [] - if columns: - for column in columns: - new_columns.append(self.get_or_new_from_json_dict( - column, CarouselColumn - )) - self.columns = new_columns - self.image_aspect_ratio = image_aspect_ratio - self.image_size = image_size - - -@deprecated(reason="Use 'from linebot.v3.messaging import ImageCarouselTemplate' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ImageCarouselTemplate(Template): - """ImageCarouselTemplate. - - https://developers.line.biz/en/reference/messaging-api/#image-carousel - - Template message with multiple images columns which can be cycled like as carousel. - """ - - def __init__(self, columns=None, **kwargs): - """__init__ method. - - :param columns: Array of columns. - Max: 10 - :type columns: list[T <= :py:class:`linebot.models.template.ImageCarouselColumn`] - :param kwargs: - """ - super(ImageCarouselTemplate, self).__init__(**kwargs) - - self.type = 'image_carousel' - - new_columns = [] - if columns: - for column in columns: - new_columns.append(self.get_or_new_from_json_dict( - column, ImageCarouselColumn - )) - self.columns = new_columns - - -@deprecated(reason="Use 'from linebot.v3.messaging import CarouselColumn' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class CarouselColumn(Base): - """CarouselColumn. - - https://developers.line.biz/en/reference/messaging-api/#column-object - """ - - def __init__(self, text=None, title=None, - thumbnail_image_url=None, image_background_color=None, - actions=None, default_action=None, **kwargs): - """__init__ method. - - :param str text: Message text. - Max: 120 characters (no image or title) - Max: 60 characters (message with an image or title) - :param str title: Title. - Max: 40 characters - :param str thumbnail_image_url: Image URL (HTTPS). JPEG or PNG. Aspect ration is 1:1.51. - Max width: 1024px, Max: 1 MB. - :param str image_background_color: Background color of image. - Specify a RGB color value. - :param actions: Action when tapped. - Max: 3 - :type actions: list[T <= :py:class:`linebot.models.actions.Action`] - :param default_action: Action when image is tapped; - set for the entire image, title, and text area - :type default_action: T <= :py:class:`linebot.models.actions.Action` - :param kwargs: - """ - super(CarouselColumn, self).__init__(**kwargs) - - self.text = text - self.title = title - self.thumbnail_image_url = thumbnail_image_url - self.image_background_color = image_background_color - self.actions = get_actions(actions) - self.default_action = get_action(default_action) - - -@deprecated(reason="Use 'from linebot.v3.messaging import ImageCarouselColumn' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ImageCarouselColumn(Base): - """ImageCarouselColumn. - - https://developers.line.biz/en/reference/messaging-api/#column-object-for-image-carousel - """ - - def __init__(self, image_url=None, action=None, **kwargs): - """__init__ method. - - :param str image_url: Image URL (HTTPS). JPEG or PNG. Aspect ration is 1:1. - Max width: 1024px, Max: 1 MB. - :param action: Action when image is tapped. Max: 5. - :type action: T <= :py:class:`linebot.models.actions.Action` - :param kwargs: - """ - super(ImageCarouselColumn, self).__init__(**kwargs) - - self.image_url = image_url - self.action = get_action(action) diff --git a/linebot/models/things.py b/linebot/models/things.py deleted file mode 100644 index b4d37ccd9..000000000 --- a/linebot/models/things.py +++ /dev/null @@ -1,161 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.things module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated - -from linebot.deprecations import ( - LineBotSdkDeprecatedIn30 -) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import ThingsContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Things(with_metaclass(ABCMeta, Base)): - """Abstract Base Class of Things.""" - - def __init__(self, device_id=None, **kwargs): - """__init__ method. - - :param str device_id: Device ID. - :param kwargs: - """ - super(Things, self).__init__(**kwargs) - self.device_id = device_id - - -@deprecated(reason="Use 'from linebot.v3.webhooks import LinkThingsContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class DeviceLink(Things): - """DeviceLink. - - https://developers.line.biz/en/reference/messaging-api/#device-link-event - - Indicates that a user linked a device with LINE. - """ - - def __init__(self, device_id=None, **kwargs): - """__init__ method. - - :param str device_id: Device ID of the device that has been linked with LINE. - :param kwargs: - """ - super(DeviceLink, self).__init__(device_id=device_id, **kwargs) - - self.type = 'link' - - -@deprecated(reason="Use 'from linebot.v3.webhooks import UnlinkThingsContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class DeviceUnlink(Things): - """DeviceUnlink. - - https://developers.line.biz/en/reference/messaging-api/#device-unlink-event - - Indicates that the user unlinked a device from LINE. - """ - - def __init__(self, device_id=None, **kwargs): - """__init__ method. - - :param str device_id: Device ID of the device that was unlinked from LINE. - :param kwargs: - """ - super(DeviceUnlink, self).__init__(device_id=device_id, **kwargs) - - self.type = 'unlink' - - -@deprecated(reason="Use 'from linebot.v3.webhooks import ScenarioResultThingsContent' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ScenarioResult(Things): - """ScenarioResult. - - https://developers.line.biz/en/reference/messaging-api/#scenario-result-event - - Indicates that an automatic communication scenario has been executed. - """ - - def __init__(self, device_id=None, result=None, **kwargs): - """__init__ method. - - :param str device_id: Device ID of the device that executed the scenario. - :param str result: ScenarioResultPayload object. - :param kwargs: - """ - super(ScenarioResult, self).__init__(device_id=device_id, **kwargs) - - self.type = 'scenarioResult' - self.result = self.get_or_new_from_json_dict( - result, ScenarioResultPayload - ) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import ScenarioResult' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ScenarioResultPayload(Base): - """ScenarioResultPayload.""" - - def __init__(self, scenario_id=None, revision=None, start_time=None, - result_code=None, end_time=None, action_results=None, - ble_notification_payload=None, error_reason=None, **kwargs): - """__init__ method. - - :param str scenario_id: Scenario ID executed. - :param long revision: Revision number. - :param long start_time: Timestamp for when execution of scenario - action started (milliseconds). - :param long end_time: Timestamp for when execution of scenario - was completed (milliseconds). - :param str result_code: Scenario execution completion status. - :param action_results: Array of actions specified in a scenario. - :type action_results: list[T <= :py:class:`linebot.models.things.ActionResult`] - :param str ble_notification_payload: Data contained in notification. - :param str error_reason: Error response. - :param kwargs: - """ - super(ScenarioResultPayload, self).__init__(**kwargs) - - self.scenario_id = scenario_id - self.revision = revision - self.start_time = start_time - self.end_time = end_time - self.result_code = result_code - self.action_results = [self.get_or_new_from_json_dict(it, ActionResult) - for it in action_results] - self.ble_notification_payload = ble_notification_payload - self.error_reason = error_reason - - -@deprecated(reason="Use 'from linebot.v3.webhooks import ActionResult' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class ActionResult(Base): - """ActionResult. - - Execution result of individual operations specified in action - """ - - def __init__(self, type=None, data=None, **kwargs): - """__init__ method. - - :param str type: Type of the executed action. - :param str data: Base64-encoded binary data. - :param kwargs: - """ - super(ActionResult, self).__init__(**kwargs) - - self.type = type - self.data = data diff --git a/linebot/models/unsend.py b/linebot/models/unsend.py deleted file mode 100644 index f1c018252..000000000 --- a/linebot/models/unsend.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.unsend module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated - -from linebot.deprecations import ( - LineBotSdkDeprecatedIn30 -) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import UnsendDetail' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class Unsend(with_metaclass(ABCMeta, Base)): - """Abstract Base Class of Unsend.""" - - def __init__(self, message_id=None, **kwargs): - """__init__ method. - - :param str message_id: The message ID of the unsent message. - :param kwargs: - """ - super(Unsend, self).__init__(**kwargs) - self.message_id = message_id diff --git a/linebot/models/video_play_complete.py b/linebot/models/video_play_complete.py deleted file mode 100644 index 9896102d8..000000000 --- a/linebot/models/video_play_complete.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.models.video_play_complete module.""" - - -from abc import ABCMeta - -from future.utils import with_metaclass - -from .base import Base - -from deprecated import deprecated - -from linebot.deprecations import ( - LineBotSdkDeprecatedIn30 -) - - -@deprecated(reason="Use 'from linebot.v3.webhooks import VideoPlayComplete' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class VideoPlayComplete(with_metaclass(ABCMeta, Base)): - """Abstract Base Class of VideoPlayComplete.""" - - def __init__(self, tracking_id=None, **kwargs): - """__init__ method. - - :param str tracking_id: the video viewing complete event occurs - when the user finishes watching the video. - Max character limit: 100. - :param kwargs: - """ - super(VideoPlayComplete, self).__init__(**kwargs) - self.tracking_id = tracking_id diff --git a/linebot/utils.py b/linebot/utils.py deleted file mode 100644 index a00bc940e..000000000 --- a/linebot/utils.py +++ /dev/null @@ -1,78 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.utils module.""" - - -import logging -import re - -import sys - -from deprecated import deprecated - -from .deprecations import ( - LineBotSdkDeprecatedIn30 -) - -LOGGER = logging.getLogger('linebot') - -PY3 = sys.version_info[0] == 3 - - -@deprecated(reason="Use 'from linebot.v3.utils import to_snake_case' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -def to_snake_case(text): - """Convert to snake case. - - :param str text: - :rtype: str - """ - s1 = re.sub('(.)([A-Z])', r'\1_\2', text) - s2 = re.sub('(.)([0-9]+)', r'\1_\2', s1) - s3 = re.sub('([0-9])([a-z])', r'\1_\2', s2) - return s3.lower() - - -@deprecated(reason="Use 'from linebot.v3.utils import to_camel_case' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -def to_camel_case(text): - """Convert to camel case. - - :param str text: - :rtype: str - """ - split = text.split('_') - return split[0] + "".join(x.title() for x in split[1:]) - - -@deprecated(reason="Use 'from linebot.v3.utils import safe_compare_digest' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -def safe_compare_digest(val1, val2): - """safe_compare_digest method. - - :param val1: string or bytes for compare - :type val1: str | bytes - :param val2: string or bytes for compare - :type val2: str | bytes - """ - if len(val1) != len(val2): - return False - - result = 0 - if PY3 and isinstance(val1, bytes) and isinstance(val2, bytes): - for i, j in zip(val1, val2): - result |= i ^ j - else: - for i, j in zip(val1, val2): - result |= (ord(i) ^ ord(j)) - - return result == 0 diff --git a/linebot/webhook.py b/linebot/webhook.py deleted file mode 100644 index dfa85a6d5..000000000 --- a/linebot/webhook.py +++ /dev/null @@ -1,308 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""linebot.webhook module.""" - -import base64 -import hashlib -import hmac -import inspect -import json - -from .exceptions import InvalidSignatureError -from .models.events import ( - MessageEvent, - FollowEvent, - UnfollowEvent, - JoinEvent, - LeaveEvent, - PostbackEvent, - BeaconEvent, - AccountLinkEvent, - MemberJoinedEvent, - MemberLeftEvent, - ThingsEvent, - UnsendEvent, - VideoPlayCompleteEvent, - UnknownEvent, -) -from .utils import LOGGER, PY3, safe_compare_digest - -from deprecated import deprecated - -from .deprecations import ( - LineBotSdkDeprecatedIn30 -) - -if hasattr(hmac, "compare_digest"): - def compare_digest(val1, val2): - """compare_digest function. - - If hmac module has compare_digest function, use it. - Or not, use linebot.utils.safe_compare_digest. - - :param val1: string or bytes for compare - :type val1: str | bytes - :param val2: string or bytes for compare - :type val2: str | bytes - :rtype: bool - :return: result - """ - return hmac.compare_digest(val1, val2) -else: - def compare_digest(val1, val2): - """compare_digest function. - - If hmac module has compare_digest function, use it. - Or not, use linebot.utils.safe_compare_digest. - - :param val1: string or bytes for compare - :type val1: str | bytes - :param val2: string or bytes for compare - :type val2: str | bytes - :rtype: bool - :return: result - """ - return safe_compare_digest(val1, val2) - - -@deprecated(reason="Use 'from linebot.v3.webhook import SignatureValidator' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class SignatureValidator(object): - """Signature validator. - - https://developers.line.biz/en/reference/messaging-api/#signature-validation - """ - - def __init__(self, channel_secret): - """__init__ method. - - :param str channel_secret: Channel secret (as text) - """ - self.channel_secret = channel_secret.encode('utf-8') - - def validate(self, body, signature): - """Check signature. - - :param str body: Request body (as text) - :param str signature: X-Line-Signature value (as text) - :rtype: bool - """ - gen_signature = hmac.new( - self.channel_secret, - body.encode('utf-8'), - hashlib.sha256 - ).digest() - - return compare_digest( - signature.encode('utf-8'), base64.b64encode(gen_signature) - ) - - -@deprecated(reason="Use 'from linebot.v3.webhook import WebhookPayload' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class WebhookPayload(object): - """Webhook Payload. - - https://developers.line.biz/en/reference/messaging-api/#request-body - """ - - def __init__(self, events=None, destination=None): - """__init__ method. - - :param events: Information about the events. - :type events: list[T <= :py:class:`linebot.models.events.Event`] - :param str destination: User ID of a bot that should receive webhook events. - """ - self.events = events - self.destination = destination - - -@deprecated(reason="Use 'from linebot.v3.webhook import WebhookParser' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class WebhookParser(object): - """Webhook Parser.""" - - def __init__(self, channel_secret): - """__init__ method. - - :param str channel_secret: Channel secret (as text) - """ - self.signature_validator = SignatureValidator(channel_secret) - - def parse(self, body, signature, as_payload=False, use_raw_message=False): - """Parse webhook request body as text. - - :param str body: Webhook request body (as text) - :param str signature: X-Line-Signature value (as text) - :param bool as_payload: (optional) True to return WebhookPayload object. - :rtype: list[T <= :py:class:`linebot.models.events.Event`] - | :py:class:`linebot.webhook.WebhookPayload` - :param bool use_raw_message: Using original Message key as attribute - :return: Events list, or WebhookPayload instance - """ - if not self.signature_validator.validate(body, signature): - raise InvalidSignatureError( - 'Invalid signature. signature=' + signature) - - body_json = json.loads(body) - events = [] - for event in body_json['events']: - event_type = event['type'] - if event_type == 'message': - events.append(MessageEvent.new_from_json_dict(event, - use_raw_message=use_raw_message)) - elif event_type == 'follow': - events.append(FollowEvent.new_from_json_dict(event)) - elif event_type == 'unfollow': - events.append(UnfollowEvent.new_from_json_dict(event)) - elif event_type == 'join': - events.append(JoinEvent.new_from_json_dict(event)) - elif event_type == 'leave': - events.append(LeaveEvent.new_from_json_dict(event)) - elif event_type == 'postback': - events.append(PostbackEvent.new_from_json_dict(event)) - elif event_type == 'beacon': - events.append(BeaconEvent.new_from_json_dict(event)) - elif event_type == 'accountLink': - events.append(AccountLinkEvent.new_from_json_dict(event)) - elif event_type == 'memberJoined': - events.append(MemberJoinedEvent.new_from_json_dict(event)) - elif event_type == 'memberLeft': - events.append(MemberLeftEvent.new_from_json_dict(event)) - elif event_type == 'things': - events.append(ThingsEvent.new_from_json_dict(event)) - elif event_type == 'unsend': - events.append(UnsendEvent.new_from_json_dict(event)) - elif event_type == 'videoPlayComplete': - events.append(VideoPlayCompleteEvent.new_from_json_dict(event)) - else: - LOGGER.info('Unknown event type. type=' + event_type) - events.append(UnknownEvent.new_from_json_dict(event)) - - if as_payload: - return WebhookPayload(events=events, destination=body_json.get('destination')) - else: - return events - - -@deprecated(reason="Use 'from linebot.v3.webhook import WebhookHandler' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.", version='3.0.0', category=LineBotSdkDeprecatedIn30) # noqa: E501 -class WebhookHandler(object): - """Webhook Handler. - - Please read https://github.com/line/line-bot-sdk-python#webhookhandler - """ - - def __init__(self, channel_secret): - """__init__ method. - - :param str channel_secret: Channel secret (as text) - """ - self.parser = WebhookParser(channel_secret) - self._handlers = {} - self._default = None - - def add(self, event, message=None): - """Add handler method. - - :param event: Specify a kind of Event which you want to handle - :type event: T <= :py:class:`linebot.models.events.Event` class - :param message: (optional) If event is MessageEvent, - specify kind of Messages which you want to handle - :type: message: T <= :py:class:`linebot.models.messages.Message` class - :rtype: func - :return: decorator - """ - - def decorator(func): - if isinstance(message, (list, tuple)): - for it in message: - self.__add_handler(func, event, message=it) - else: - self.__add_handler(func, event, message=message) - - return func - - return decorator - - def default(self): - """Set default handler method. - - :rtype: func - :return: decorator - """ - - def decorator(func): - self._default = func - return func - - return decorator - - def handle(self, body, signature, use_raw_message=False): - """Handle webhook. - - :param str body: Webhook request body (as text) - :param str signature: X-Line-Signature value (as text) - :param bool use_raw_message: Using original Message key as attribute - """ - payload = self.parser.parse(body, signature, as_payload=True, - use_raw_message=use_raw_message) - - for event in payload.events: - func = None - key = None - - if isinstance(event, MessageEvent): - key = self.__get_handler_key( - event.__class__, event.message.__class__) - func = self._handlers.get(key, None) - - if func is None: - key = self.__get_handler_key(event.__class__) - func = self._handlers.get(key, None) - - if func is None: - func = self._default - - if func is None: - LOGGER.info('No handler of ' + key + ' and no default handler') - else: - self.__invoke_func(func, event, payload) - - def __add_handler(self, func, event, message=None): - key = self.__get_handler_key(event, message=message) - self._handlers[key] = func - - @classmethod - def __invoke_func(cls, func, event, payload): - (has_varargs, args_count) = cls.__get_args_count(func) - if has_varargs or args_count == 2: - func(event, payload.destination) - elif args_count == 1: - func(event) - else: - func() - - @staticmethod - def __get_args_count(func): - if PY3: - arg_spec = inspect.getfullargspec(func) - return (arg_spec.varargs is not None, len(arg_spec.args)) - else: - arg_spec = inspect.getargspec(func) - return (arg_spec.varargs is not None, len(arg_spec.args)) - - @staticmethod - def __get_handler_key(event, message=None): - if message is None: - return event.__name__ - else: - return event.__name__ + '_' + message.__name__ diff --git a/requirements.txt b/requirements.txt index 57bc81282..a8c11bca8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,4 +5,3 @@ future >= 1.0.0 pydantic >=2.0.3, <3 aenum >= 3.1.11, <4 python_dateutil >= 2.5.3, <3 -Deprecated>=1.2.18 diff --git a/setup.py b/setup.py index f58200bb8..399bf92c7 100644 --- a/setup.py +++ b/setup.py @@ -16,9 +16,8 @@ import os import re import sys -import subprocess -from setuptools import setup, Command, find_packages +from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand __version__ = '' @@ -54,125 +53,6 @@ def run_tests(self): sys.exit(errno) -class CodegenCommand(Command): - user_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - basedir = os.path.abspath(os.path.dirname(__file__)) - - header = ( - "# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" - "#\n" - "# *** DO NOT EDIT THIS FILE ***\n" - "#\n" - "# 1) Modify linebot/api.py\n" - "# 2) Run `python setup.py codegen`\n" - "#\n" - "# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" - "\n" - ) - - with open(f"{basedir}/linebot/api.py", "r") as original: - source = original.read() - import re - - async_source = header + source - async_source = re.sub(" def (?!__init__)", " async def ", - async_source) - async_source = re.sub("from .http_client import HttpClient, RequestsHttpClient", "", - async_source) - - # Change the signature of the __init__. - # self, channel_access_token - async_source = re.sub(r"def __init__\(self, channel_access_token,", - "def __init__(self, channel_access_token, async_http_client,", - async_source) - async_source = re.sub( - r",\s*timeout=HttpClient.DEFAULT_TIMEOUT, http_client=RequestsHttpClient", - "", async_source) - async_source = re.sub( - r"if http_client:\n" - + r"\s*self.http_client = http_client\(timeout=timeout\)\n" - + r"\s*else:\n" - + r"\s*self.http_client = RequestsHttpClient\(timeout=timeout\)", - "self.async_http_client = async_http_client", async_source) - async_source = re.sub( - r"\"\"\"__init__ method.*?\"\"\"\n", - '"""__init__ method.' + "\n\n" - + " :param str channel_access_token: Your channel access token\n" - + " :param str endpoint: (optional) Default is https://api.line.me\n" - + " :param str data_endpoint: (optional) Default is https://api-data.line.me\n" - + "\n\"\"\"\n" - , async_source, flags=re.DOTALL) - async_source = re.sub("'line-bot-sdk-python/'", '"line-bot-sdk-python-async/"', - async_source) - - async_source = re.sub('"""linebot.api module."""', '"""linebot.async_api module."""', - async_source) - async_source = re.sub( - "self.(_get|_post|_delete|_put)", "await self.\\1", async_source - ) - async_source = re.sub( - "self.http_client.(get|post|delete|put)", "await self.async_http_client.\\1", - async_source - ) - async_source = re.sub( - "response.json", "(await response.json)", async_source - ) - async_source = re.sub( - "from .http_client import HttpClient, RequestsHttpClient", - "from .async_http_client import AsyncHttpClient, AiohttpAsyncHttpClient", - async_source - ) - async_source = re.sub( - "linebot.http_client.RequestsHttpClient", - "linebot.async_http_client.AiohttpAsyncHttpClient", - async_source - ) - async_source = re.sub( - "HttpClient.DEFAULT_TIMEOUT", "AsyncHttpClient.DEFAULT_TIMEOUT", async_source - ) - async_source = re.sub( - "RequestsHttpClient", "AiohttpAsyncHttpClient", async_source - ) - async_source = re.sub( - "Default is self.http_client.timeout", "Default is self.async_http_client.timeout", - async_source - ) - async_source = re.sub( - "self.__check_error", "await self.__check_error", async_source - ) - async_source = re.sub( - "class LineBotApi", - "class AsyncLineBotApi", async_source - ) - async_source = re.sub("stream=(stream|False|True), ", "", async_source) - - async_source = re.sub("MessagingApiBlob'", "AsyncMessagingApiBlob'", async_source) - async_source = re.sub("MessagingApiBlob\\(", "AsyncMessagingApiBlob(", async_source) - async_source = re.sub("MessagingApi'", "AsyncMessagingApi'", async_source) - async_source = re.sub("MessagingApi\\(", "AsyncMessagingApi(", async_source) - async_source = re.sub("ManageAudience'", "AsyncManageAudience'", async_source) - async_source = re.sub("ManageAudience\\(", "AsyncManageAudience(", async_source) - async_source = re.sub("Insight'", "AsyncInsight'", async_source) - async_source = re.sub("Insight\\(", "AsyncInsight(", async_source) - async_source = re.sub("ChannelAccessToken'", "AsyncChannelAccessToken'", async_source) - async_source = re.sub("ChannelAccessToken\\(", "AsyncChannelAccessToken(", async_source) - - with open(f"{basedir}/linebot/async_api.py", "w") as output: - output.write(async_source) - - subprocess.check_call( - [sys.executable, "-m", "black", f"{basedir}/linebot/async_api.py"], - ) - - with open('README.rst', 'r') as fd: long_description = fd.read() @@ -193,7 +73,6 @@ def run(self): tests_require=_requirements_test(), cmdclass={ 'test': PyTest, - 'codegen': CodegenCommand }, classifiers=[ "Development Status :: 5 - Production/Stable", diff --git a/tests/api/__init__.py b/tests/api/__init__.py deleted file mode 100644 index 64a4ff91f..000000000 --- a/tests/api/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. diff --git a/tests/api/test_channel_access_token_v2_1.py b/tests/api/test_channel_access_token_v2_1.py deleted file mode 100644 index 4673b2146..000000000 --- a/tests/api/test_channel_access_token_v2_1.py +++ /dev/null @@ -1,187 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import sys -import unittest - -import responses - -from linebot import ( - LineBotApi -) - -PY3 = sys.version_info[0] == 3 -if PY3: - from urllib import parse -else: - import urlparse as parse - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - self.access_token = 'W1TeHCgfH2Liwa.....' - self.expires_in = 2592000 - self.token_type = 'Bearer' - self.client_assertion = 'eyJhbGciOiJSUzI.q....' - self.client_id = 'client_id' - self.client_secret = 'client_secret' - self.client_assertion_type = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer' - self.key_id = 'sDTOzw5wIfxxxxPEzcmeQA' - self.scope = 'profile chat_message.write' - - @responses.activate - def test_issue_channel_access_token_v2_1(self): - endpoint = LineBotApi.DEFAULT_API_ENDPOINT + '/oauth2/v2.1/token' - responses.add( - responses.POST, - endpoint, - json={ - 'access_token': self.access_token, - 'expires_in': self.expires_in, - 'token_type': self.token_type, - 'key_id': self.key_id - }, - status=200 - ) - - issue_access_token_response = self.tested.issue_channel_access_token_v2_1( - self.client_assertion - ) - - request = responses.calls[0].request - self.assertEqual('POST', request.method) - self.assertEqual(endpoint, request.url) - self.assertEqual('application/x-www-form-urlencoded', request.headers['content-type']) - self.assertEqual(self.access_token, issue_access_token_response.access_token) - self.assertEqual(self.expires_in, issue_access_token_response.expires_in) - self.assertEqual(self.token_type, issue_access_token_response.token_type) - - encoded_body = parse.parse_qs(request.body) - self.assertEqual('client_credentials', encoded_body['grant_type'][0]) - self.assertEqual(self.client_assertion_type, encoded_body['client_assertion_type'][0]) - self.assertEqual(self.client_assertion, encoded_body['client_assertion'][0]) - - @responses.activate - def test_get_channel_access_token_v2_1(self): - - endpoint = LineBotApi.DEFAULT_API_ENDPOINT + '/oauth2/v2.1/tokens' - responses.add( - responses.GET, - endpoint, - json={ - 'access_tokens': [ - 'fgIkeLcl3.....', - 'eyJhbGciO.....', - 'oeLklsSi7.....' - ] - }, - status=200 - ) - channel_access_tokens_response = self.tested.get_channel_access_tokens_v2_1( - self.client_assertion - ) - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - parse.unquote(request.url), - parse.unquote('{}?client_assertion={}&client_assertion_type={}'.format( - endpoint, self.client_assertion, self.client_assertion_type - )) - ) - self.assertEqual(channel_access_tokens_response.access_tokens, [ - 'fgIkeLcl3.....', - 'eyJhbGciO.....', - 'oeLklsSi7.....' - ]) - - @responses.activate - def test_revoke_channel_access_token_v2_1(self): - endpoint = LineBotApi.DEFAULT_API_ENDPOINT + '/oauth2/v2.1/revoke' - - responses.add( - responses.POST, - endpoint, - status=200 - ) - - self.tested.revoke_channel_access_token_v2_1( - self.client_id, self.client_secret, self.access_token - ) - - request = responses.calls[0].request - self.assertEqual('POST', request.method) - self.assertEqual(endpoint, request.url) - - encoded_body = parse.parse_qs(request.body) - self.assertEqual(self.client_id, encoded_body['client_id'][0]) - self.assertEqual(self.client_secret, encoded_body['client_secret'][0]) - self.assertEqual(self.access_token, encoded_body['access_token'][0]) - - @responses.activate - def test_verify_channel_access_token_v2_1(self): - endpoint = LineBotApi.DEFAULT_API_ENDPOINT + '/oauth2/v2.1/verify' - - responses.add( - responses.GET, - endpoint, - status=200, - json={ - 'client_id': self.client_id, - 'expires_in': self.expires_in, - 'scope': self.scope, - }, - ) - - self.tested.verify_channel_access_token_v2_1(self.access_token) - - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual( - parse.unquote(request.url), - parse.unquote('{}?access_token={}'.format( - endpoint, self.access_token - )) - ) - - @responses.activate - def test_get_channel_token_key_ids_v2_1(self): - endpoint = LineBotApi.DEFAULT_API_ENDPOINT + '/oauth2/v2.1/tokens/kid' - - responses.add( - responses.GET, - endpoint, - status=200, - json={ - 'kids': [self.key_id], - }, - ) - - self.tested.get_channel_token_key_ids_v2_1(self.client_assertion, self.client_assertion_type) - - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual( - parse.unquote(request.url), - parse.unquote('{}?client_assertion={}&client_assertion_type={}'.format( - endpoint, self.client_assertion, self.client_assertion_type - )) - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_error_handle.py b/tests/api/test_error_handle.py deleted file mode 100644 index dba3fe764..000000000 --- a/tests/api/test_error_handle.py +++ /dev/null @@ -1,125 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.exceptions import ( - LineBotApiError -) -from linebot.models import ( - TextSendMessage -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - self.request_id = 'f70dd685-499a-4231-a441-f24b8d4fba21' - self.headers = {'X-Line-Request-Id': self.request_id, 'HOGE': 'FUGA'} - - @responses.activate - def test_error_handle(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={ - "message": "Invalid reply token" - }, - headers=self.headers, - status=401 - ) - - try: - self.tested.push_message('to', TextSendMessage(text='hoge')) - except LineBotApiError as e: - self.assertEqual(e.status_code, 401) - self.assertEqual(e.error.message, 'Invalid reply token') - self.assertEqual(e.request_id, self.request_id) - self.assertEqual(e.headers['HOGE'], 'FUGA') - - @responses.activate - def test_error_with_detail_handle(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={ - "message": "The request body has 2 error(s)", - "details": [ - { - "message": "May not be empty", - "property": "messages[0].text" - }, - { - "message": "Must be one of the following values: [text" - ", image, video, audio, location, sticker, " - "richmessage, template, imagemap]", - "property": "messages[1].type" - } - ] - }, - headers=self.headers, - status=400 - ) - - try: - self.tested.push_message( - 'to', - TextSendMessage(text='hoge') - ) - except LineBotApiError as e: - self.assertEqual(e.status_code, 400) - self.assertEqual(e.error.message, 'The request body has 2 error(s)') - self.assertEqual(e.error.details[0].message, 'May not be empty') - self.assertEqual(e.error.details[0].property, 'messages[0].text') - self.assertEqual( - e.error.details[1].message, "Must be one of the following " - "values: [text" - ", image, video, audio, " - "location, sticker, " - "richmessage, template, imagemap]" - ) - self.assertEqual(e.error.details[1].property, 'messages[1].type') - self.assertEqual(e.request_id, self.request_id) - self.assertEqual(e.headers['HOGE'], 'FUGA') - - @responses.activate - def test_error_handle_get_message_content(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_DATA_ENDPOINT + '/v2/bot/message/1/content', - json={ - "message": "Invalid reply token" - }, - headers=self.headers, - status=404 - ) - - try: - self.tested.get_message_content(1) - except LineBotApiError as e: - self.assertEqual(e.status_code, 404) - self.assertEqual(e.error.message, 'Invalid reply token') - self.assertEqual(e.request_id, self.request_id) - self.assertEqual(e.headers['HOGE'], 'FUGA') - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_get_bot_info.py b/tests/api/test_get_bot_info.py deleted file mode 100644 index b1f9c8937..000000000 --- a/tests/api/test_get_bot_info.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - @responses.activate - def test_get_bot_info(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/info', - json={ - "userId": "Ub9952f8...", - "basicId": "@216ru...", - "premiumId": "@example", - "displayName": "Example name", - "pictureUrl": "https://obs.line-apps.com/...", - "chatMode": "chat", - "markAsReadMode": "manual", - }, - status=200 - ) - - bot = self.tested.get_bot_info() - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/info') - self.assertEqual(bot.user_id, 'Ub9952f8...') - self.assertEqual(bot.basic_id, '@216ru...') - self.assertEqual(bot.premium_id, '@example') - self.assertEqual(bot.display_name, 'Example name') - self.assertEqual(bot.picture_url, 'https://obs.line-apps.com/...') - self.assertEqual(bot.chat_mode, 'chat') - self.assertEqual(bot.mark_as_read_mode, 'manual') - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_get_content.py b/tests/api/test_get_content.py deleted file mode 100644 index c6188b3b1..000000000 --- a/tests/api/test_get_content.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - def test_get_content(self): - pass - # message_content = self.tested.get_content(12345) - # with open('/tmp/content.jpg', 'wb') as f: - # for chunk in message_content.iter_content(): - # f.write(chunk) - # f.close() - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_get_custom_aggregation_units.py b/tests/api/test_get_custom_aggregation_units.py deleted file mode 100644 index 84c5e3652..000000000 --- a/tests/api/test_get_custom_aggregation_units.py +++ /dev/null @@ -1,122 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - @responses.activate - def test_get_number_of_units_used_this_month(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/aggregation/info', - json={ - 'numOfCustomAggregationUnits': 22 - }, - status=200 - ) - - usage = self.tested.get_number_of_units_used_this_month() - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/aggregation/info') - self.assertEqual(usage.num_of_custom_aggregation_units, 22) - - @responses.activate - def test_get_name_list_of_units_used_this_month(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/aggregation/list', - json={ - 'customAggregationUnits': ['promotion_a', 'promotion_b'] - }, - status=200 - ) - - name_list = self.tested.get_name_list_of_units_used_this_month(30) - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/aggregation/list?limit=30') - self.assertEqual(name_list.custom_aggregation_units, - ['promotion_a', 'promotion_b']) - self.assertEqual(name_list.next, None) - - @responses.activate - def test_get_name_list_of_units_used_this_month_with_start(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/aggregation/list', - json={ - 'customAggregationUnits': ['promotion_a', 'promotion_b'], - 'next': 'continuationToken2' - }, - status=200 - ) - - name_list = self.tested.get_name_list_of_units_used_this_month(start='continuationToken1') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/message/aggregation/list?limit=100&start=continuationToken1') - self.assertEqual(name_list.custom_aggregation_units, ['promotion_a', 'promotion_b']) - self.assertEqual(name_list.next, 'continuationToken2') - - @responses.activate - def test_get_name_list_of_units_used_this_month_with_start_and_limit(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/aggregation/list', - json={ - 'customAggregationUnits': ['promotion_a', 'promotion_b'], - 'next': 'continuationToken2' - }, - status=200 - ) - - name_list = self.tested.get_name_list_of_units_used_this_month(limit=2, - start='continuationToken1') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/message/aggregation/list?limit=2&start=continuationToken1') - self.assertEqual(name_list.custom_aggregation_units, - ['promotion_a', 'promotion_b']) - self.assertEqual(name_list.next, 'continuationToken2') - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_get_delivery.py b/tests/api/test_get_delivery.py deleted file mode 100644 index ced7eb949..000000000 --- a/tests/api/test_get_delivery.py +++ /dev/null @@ -1,109 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - self.date = '20190101' - - @responses.activate - def test_get_delivery_broadcast(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/message/delivery/broadcast?date={}'.format(self.date), - json={ - 'status': 'ready', - 'success': 10000 - }, - status=200 - ) - - res = self.tested.get_message_delivery_broadcast(self.date) - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual('ready', res.status) - self.assertEqual(10000, res.success) - - @responses.activate - def test_get_delivery_push(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/message/delivery/push?date={}'.format(self.date), - json={ - 'status': 'ready', - 'success': 10000 - }, - status=200 - ) - - res = self.tested.get_message_delivery_push(self.date) - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual('ready', res.status) - self.assertEqual(10000, res.success) - - @responses.activate - def test_get_delivery_reply(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/message/delivery/reply?date={}'.format(self.date), - json={ - 'status': 'ready', - 'success': 10000 - }, - status=200 - ) - - res = self.tested.get_message_delivery_reply(self.date) - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual('ready', res.status) - self.assertEqual(10000, res.success) - - @responses.activate - def test_get_delivery_multicast(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/message/delivery/multicast?date={}'.format(self.date), - json={ - 'status': 'ready', - 'success': 10000 - }, - status=200 - ) - - res = self.tested.get_message_delivery_multicast(self.date) - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual('ready', res.status) - self.assertEqual(10000, res.success) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_get_group.py b/tests/api/test_get_group.py deleted file mode 100644 index 967d8be83..000000000 --- a/tests/api/test_get_group.py +++ /dev/null @@ -1,74 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - @responses.activate - def test_get_group_summary(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/group_id/summary', - json={ - "groupId": "Ca56f94637c...", - "groupName": "Group name", - "pictureUrl": "https://example.com/abcdefghijklmn" - }, - status=200 - ) - - group = self.tested.get_group_summary('group_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/group_id/summary') - self.assertEqual(group.group_id, 'Ca56f94637c...') - self.assertEqual(group.group_name, 'Group name') - self.assertEqual(group.picture_url, 'https://example.com/abcdefghijklmn') - - @responses.activate - def test_get_group_members_count(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/group_id/members/count', - json={"count": 3}, - status=200 - ) - - count = self.tested.get_group_members_count('group_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/group_id/members/count') - self.assertEqual(count, 3) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_get_insight.py b/tests/api/test_get_insight.py deleted file mode 100644 index 92634fbb9..000000000 --- a/tests/api/test_get_insight.py +++ /dev/null @@ -1,341 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - GenderInsight, AreaInsight, AgeInsight, AppTypeInsight, SubscriptionPeriodInsight -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - self.date = '20190101' - self.request_id = 'f70dd685-499a-4231-a441-f24b8d4fba21' - - @responses.activate - def test_get_insight_message_delivery(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/insight/message/delivery?date={date}'.format(date=self.date), - json={ - 'status': 'ready', - 'broadcast': 100, - 'targeting': 200, - 'autoResponse': 300, - 'welcomeResponse': 400, - 'chat': 500, - 'apiBroadcast': 600, - 'apiPush': 700, - 'apiMulticast': 800, - }, - status=200 - ) - - res = self.tested.get_insight_message_delivery(self.date) - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual('ready', res.status) - self.assertEqual(100, res.broadcast) - self.assertEqual(200, res.targeting) - self.assertEqual(300, res.auto_response) - self.assertEqual(400, res.welcome_response) - self.assertEqual(500, res.chat) - self.assertEqual(600, res.api_broadcast) - self.assertEqual(700, res.api_push) - self.assertEqual(800, res.api_multicast) - self.assertEqual(None, res.api_reply) - - @responses.activate - def test_get_insight_followers(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/insight/followers?date={date}'.format(date=self.date), - json={ - 'status': 'ready', - 'followers': 100, - 'targetedReaches': 200, - 'blocks': 300 - }, - status=200 - ) - - res = self.tested.get_insight_followers(self.date) - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual('ready', res.status) - self.assertEqual(100, res.followers) - self.assertEqual(200, res.targeted_reaches) - self.assertEqual(300, res.blocks) - - @responses.activate - def test_get_insight_demographic(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/insight/demographic', - json={ - 'available': True, - 'genders': [ - { - 'gender': 'unknown', - 'percentage': 37.6 - }, - { - 'gender': 'male', - 'percentage': 31.8 - }, - { - 'gender': 'female', - 'percentage': 30.6 - } - ], - 'ages': [ - { - 'age': 'unknown', - 'percentage': 37.6 - }, - { - 'age': 'from50', - 'percentage': 17.3 - }, - ], - 'areas': [ - { - 'area': 'unknown', - 'percentage': 50.5 - }, - { - 'area': 'Tokyo', - 'percentage': 49.5 - }, - ], - 'appTypes': [ - { - 'appType': 'ios', - 'percentage': 62.4 - }, - { - 'appType': 'android', - 'percentage': 27.7 - }, - { - 'appType': 'others', - 'percentage': 9.9 - } - ], - 'subscriptionPeriods': [ - { - 'subscriptionPeriod': 'over365days', - 'percentage': 96.4 - }, - { - 'subscriptionPeriod': 'within365days', - 'percentage': 1.9 - }, - { - 'subscriptionPeriod': 'within180days', - 'percentage': 1.2 - }, - { - 'subscriptionPeriod': 'within90days', - 'percentage': 0.5 - }, - { - 'subscriptionPeriod': 'within30days', - 'percentage': 0.1 - }, - { - 'subscriptionPeriod': 'within7days', - 'percentage': 0 - } - ] - }, - status=200 - ) - - res = self.tested.get_insight_demographic() - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual(True, res.available) - self.assertIn(GenderInsight(gender='male', percentage=31.8), res.genders) - self.assertIn(AgeInsight(age='from50', percentage=17.3), res.ages) - self.assertIn(AreaInsight(area='Tokyo', percentage=49.5), res.areas) - self.assertIn(AppTypeInsight(app_type='ios', percentage=62.4), res.app_types) - self.assertIn( - SubscriptionPeriodInsight(subscription_period='over365days', percentage=96.4), - res.subscription_periods - ) - - @responses.activate - def test_get_insight_message_event(self): - json = { - 'overview': { - 'requestId': 'f70dd685-499a-4231-a441-f24b8d4fba21', - 'timestamp': 1568214000, - 'delivered': 32, - 'uniqueImpression': 4, - 'uniqueClick': None, - 'uniqueMediaPlayed': 2, - 'uniqueMediaPlayed100Percent': -1 - }, - 'messages': [ - { - 'seq': 1, - 'impression': 18, - 'mediaPlayed': 11, - 'mediaPlayed25Percent': -1, - 'mediaPlayed50Percent': -1, - 'mediaPlayed75Percent': -1, - 'mediaPlayed100Percent': -1, - 'uniqueMediaPlayed': 2, - 'uniqueMediaPlayed25Percent': -1, - 'uniqueMediaPlayed50Percent': -1, - 'uniqueMediaPlayed75Percent': -1, - 'uniqueMediaPlayed100Percent': -1 - } - ], - 'clicks': [ - { - 'seq': 1, - 'url': 'https://www.yahoo.co.jp/', - 'click': -1, - 'uniqueClick': -1, - 'uniqueClickOfRequest': -1 - }, - { - 'seq': 1, - 'url': 'https://www.google.com/?hl=ja', - 'click': -1, - 'uniqueClick': -1, - 'uniqueClickOfRequest': -1 - } - ] - } - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/insight/message/event?requestId={request_id}'.format(request_id=self.request_id), - status=200, - json=json, - ) - - res = self.tested.get_insight_message_event(self.request_id) - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/insight/message/event?requestId={request_id}'.format(request_id=self.request_id) - ) - - self.assertEqual(res.overview.timestamp, json['overview']['timestamp']) - self.assertEqual(res.overview.unique_media_played_100_percent, json['overview']['uniqueMediaPlayed100Percent']) - self.assertEqual(res.messages[0].seq, json['messages'][0]['seq']) - self.assertEqual(res.messages[0].media_played_50_percent, json['messages'][0]['mediaPlayed50Percent']) - self.assertEqual(res.clicks[0].url, json['clicks'][0]['url']) - self.assertEqual(res.clicks[0].unique_click_of_request, json['clicks'][0]['uniqueClickOfRequest']) - - @responses.activate - def test_get_statistics_per_unit(self): - json = { - 'overview': { - "uniqueImpression": 40, - "uniqueClick": 30, - "uniqueMediaPlayed": 25, - "uniqueMediaPlayed100Percent": None - }, - 'messages': [ - { - 'seq': 1, - 'impression': 42, - 'mediaPlayed': 30, - 'mediaPlayed25Percent': None, - 'mediaPlayed50Percent': None, - 'mediaPlayed75Percent': None, - 'mediaPlayed100Percent': None, - 'uniqueMediaPlayed': 25, - 'uniqueMediaPlayed25Percent': None, - 'uniqueMediaPlayed50Percent': None, - 'uniqueMediaPlayed75Percent': None, - 'uniqueMediaPlayed100Percent': None - } - ], - 'clicks': [ - { - 'seq': 1, - 'url': 'https://developers.line.biz/', - 'click': 35, - 'uniqueClick': 25, - 'uniqueClickOfRequest': None - }, - { - 'seq': 1, - 'url': 'https://developers.line.biz/', - 'click': 20, - 'uniqueClick': None, - 'uniqueClickOfRequest': None - } - ] - } - request_param = { - 'custom_aggregation_unit': 'promotion_a', - 'from': '20210301', - 'to': '20210331' - } - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/insight/message/event/aggregation' - '?customAggregationUnit={custom_aggregation_unit}' - '&from={from_date}&to={to_date}'.format( - custom_aggregation_unit=request_param['custom_aggregation_unit'], - from_date=request_param['from'], to_date=request_param['to']), - status=200, - json=json, - ) - - res = self.tested.get_statistics_per_unit( - request_param['custom_aggregation_unit'], request_param['from'], request_param['to']) - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/insight/message/event/aggregation' - '?customAggregationUnit={custom_aggregation_unit}' - '&from={from_date}&to={to_date}'.format( - custom_aggregation_unit=request_param['custom_aggregation_unit'], - from_date=request_param['from'], to_date=request_param['to']) - ) - - self.assertEqual(res.overview.unique_media_played_100_percent, json['overview']['uniqueMediaPlayed100Percent']) - self.assertEqual(res.messages[0].seq, json['messages'][0]['seq']) - self.assertEqual(res.messages[0].media_played_50_percent, json['messages'][0]['mediaPlayed50Percent']) - self.assertEqual(res.clicks[0].url, json['clicks'][0]['url']) - self.assertEqual(res.clicks[0].unique_click_of_request, json['clicks'][0]['uniqueClickOfRequest']) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_get_member_ids.py b/tests/api/test_get_member_ids.py deleted file mode 100644 index fa77417b7..000000000 --- a/tests/api/test_get_member_ids.py +++ /dev/null @@ -1,189 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - @responses.activate - def test_get_group_member_ids(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/group_id/members/ids', - json={ - 'memberIds': ['U1', 'U2'] - }, - status=200 - ) - - member_ids_response = self.tested.get_group_member_ids('group_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/group_id/members/ids') - self.assertEqual(member_ids_response.member_ids, ['U1', 'U2']) - self.assertEqual(member_ids_response.next, None) - - @responses.activate - def test_get_group_member_ids_with_start(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/group_id/members/ids', - json={ - 'memberIds': ['U1', 'U2'], - 'next': 'continuationToken2' - }, - status=200 - ) - - member_ids_response = self.tested.get_group_member_ids('group_id', - start='continuationToken1') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/group/group_id/members/ids?start=continuationToken1') - self.assertEqual(member_ids_response.member_ids, ['U1', 'U2']) - self.assertEqual(member_ids_response.next, 'continuationToken2') - - @responses.activate - def test_get_room_member_ids(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/room/room_id/members/ids', - json={ - 'memberIds': ['U1', 'U2'] - }, - status=200 - ) - - member_ids_response = self.tested.get_room_member_ids('room_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/room/room_id/members/ids') - self.assertEqual(member_ids_response.member_ids, ['U1', 'U2']) - self.assertEqual(member_ids_response.next, None) - - @responses.activate - def test_get_room_member_ids_with_start(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/room/room_id/members/ids', - json={ - 'memberIds': ['U1', 'U2'], - 'next': 'continuationToken2' - }, - status=200 - ) - - member_ids_response = self.tested.get_room_member_ids('room_id', - start='continuationToken1') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/room/room_id/members/ids?start=continuationToken1') - self.assertEqual(member_ids_response.member_ids, ['U1', 'U2']) - self.assertEqual(member_ids_response.next, 'continuationToken2') - - @responses.activate - def test_get_follower_user_ids(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/followers/ids', - json={ - 'userIds': ['U1', 'U2'] - }, - status=200 - ) - - member_ids_response = self.tested.get_followers_ids() - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/followers/ids?limit=300') - self.assertEqual(member_ids_response.user_ids, ['U1', 'U2']) - self.assertEqual(member_ids_response.next, None) - - @responses.activate - def test_get_follower_user_ids_with_start(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/followers/ids', - json={ - 'userIds': ['U1', 'U2'], - 'next': 'continuationToken2' - }, - status=200 - ) - - member_ids_response = self.tested.get_followers_ids(start='continuationToken1') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/followers/ids?limit=300&start=continuationToken1') - self.assertEqual(member_ids_response.user_ids, ['U1', 'U2']) - self.assertEqual(member_ids_response.next, 'continuationToken2') - - @responses.activate - def test_get_follower_user_ids_with_start_and_limit(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/followers/ids', - json={ - 'userIds': ['U1', 'U2'], - 'next': 'continuationToken2' - }, - status=200 - ) - - member_ids_response = self.tested.get_followers_ids(limit=2, start='continuationToken1') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/followers/ids?limit=2&start=continuationToken1') - self.assertEqual(member_ids_response.user_ids, ['U1', 'U2']) - self.assertEqual(member_ids_response.next, 'continuationToken2') - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_get_member_profile.py b/tests/api/test_get_member_profile.py deleted file mode 100644 index 8a1dbd350..000000000 --- a/tests/api/test_get_member_profile.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - @responses.activate - def test_get_group_member_profile(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/group_id/member/user_id', - json={ - "displayName": "LINE taro", - "userId": "Uxxxxxxxxxxxxxx...", - "pictureUrl": "http://obs.line-apps.com/..." - }, - status=200 - ) - - profile = self.tested.get_group_member_profile('group_id', 'user_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/group_id/member/user_id') - self.assertEqual(profile.display_name, 'LINE taro') - self.assertEqual(profile.user_id, 'Uxxxxxxxxxxxxxx...') - self.assertEqual(profile.picture_url, 'http://obs.line-apps.com/...') - - @responses.activate - def test_get_room_member_profile(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/room/room_id/member/user_id', - json={ - "displayName": "LINE taro", - "userId": "Uxxxxxxxxxxxxxx...", - "pictureUrl": "http://obs.line-apps.com/..." - }, - status=200 - ) - - profile = self.tested.get_room_member_profile('room_id', 'user_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/room/room_id/member/user_id') - self.assertEqual(profile.display_name, 'LINE taro') - self.assertEqual(profile.user_id, 'Uxxxxxxxxxxxxxx...') - self.assertEqual(profile.picture_url, 'http://obs.line-apps.com/...') - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_get_message_quota.py b/tests/api/test_get_message_quota.py deleted file mode 100644 index 8192e9a4a..000000000 --- a/tests/api/test_get_message_quota.py +++ /dev/null @@ -1,75 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - @responses.activate - def test_get_message_quota(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/quota', - json={ - 'type': 'limited', - 'value': 1000 - }, - status=200 - ) - res = self.tested.get_message_quota() - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual('limited', res.type) - self.assertEqual(1000, res.value) - - @responses.activate - def test_get_message_quota_2(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/quota', - json={'type': 'none'}, - status=200 - ) - res = self.tested.get_message_quota() - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual('none', res.type) - - @responses.activate - def test_get_message_quota_consumption(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/quota/consumption', - json={'totalUsage': 500}, - status=200 - ) - res = self.tested.get_message_quota_consumption() - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual(500, res.total_usage) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_get_profile.py b/tests/api/test_get_profile.py deleted file mode 100644 index 94a382a43..000000000 --- a/tests/api/test_get_profile.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - @responses.activate - def test_get_profile(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/profile/user_id', - json={ - "displayName": "LINE taro", - "userId": "Uxxxxxxxxxxxxxx...", - "pictureUrl": "http://obs.line-apps.com/...", - "statusMessage": "Hello, LINE!", - "language": "en" - }, - status=200 - ) - - profile = self.tested.get_profile('user_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/profile/user_id') - self.assertEqual(profile.display_name, 'LINE taro') - self.assertEqual(profile.user_id, 'Uxxxxxxxxxxxxxx...') - self.assertEqual(profile.picture_url, 'http://obs.line-apps.com/...') - self.assertEqual(profile.status_message, 'Hello, LINE!') - self.assertEqual(profile.language, 'en') - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_get_room.py b/tests/api/test_get_room.py deleted file mode 100644 index 5174f0021..000000000 --- a/tests/api/test_get_room.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - @responses.activate - def test_get_room_members_count(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/room/room_id/members/count', - json={"count": 3}, - status=200 - ) - - count = self.tested.get_room_members_count('room_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/room/room_id/members/count') - self.assertEqual(count, 3) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_get_webhook_endpoint.py b/tests/api/test_get_webhook_endpoint.py deleted file mode 100644 index ae69be658..000000000 --- a/tests/api/test_get_webhook_endpoint.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - @responses.activate - def test_get_webhook_endpoint(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/channel/webhook/endpoint', - json={ - "endpoint": "https://example.herokuapp.com/test", - "active": True, - }, - status=200 - ) - - webhook = self.tested.get_webhook_endpoint() - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/channel/webhook/endpoint') - self.assertEqual(webhook.endpoint, 'https://example.herokuapp.com/test') - self.assertEqual(webhook.active, True) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_issue_channel_token.py b/tests/api/test_issue_channel_token.py deleted file mode 100644 index b0d5dbc63..000000000 --- a/tests/api/test_issue_channel_token.py +++ /dev/null @@ -1,76 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import sys -import unittest - -import responses - -from linebot import ( - LineBotApi -) - -PY3 = sys.version_info[0] == 3 -if PY3: - from urllib import parse -else: - import urlparse as parse - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - self.endpoint = LineBotApi.DEFAULT_API_ENDPOINT + '/v2/oauth/accessToken' - self.access_token = "W1TeHCgfH2Liwa....." - self.expires_in = 2592000 - self.token_type = "Bearer" - self.client_id = 'client_id' - self.client_secret = 'client_secret' - - @responses.activate - def test_issue_line_token(self): - responses.add( - responses.POST, - self.endpoint, - json={ - "access_token": self.access_token, - "expires_in": self.expires_in, - "token_type": self.token_type - }, - status=200 - ) - - issue_access_token_response = self.tested.issue_channel_token( - self.client_id, - self.client_secret - ) - - request = responses.calls[0].request - self.assertEqual('POST', request.method) - self.assertEqual(self.endpoint, request.url) - self.assertEqual('application/x-www-form-urlencoded', request.headers['content-type']) - self.assertEqual(self.access_token, issue_access_token_response.access_token) - self.assertEqual(self.expires_in, issue_access_token_response.expires_in) - self.assertEqual(self.token_type, issue_access_token_response.token_type) - - encoded_body = parse.parse_qs(request.body) - self.assertEqual('client_credentials', encoded_body['grant_type'][0]) - self.assertEqual(self.client_id, encoded_body['client_id'][0]) - self.assertEqual(self.client_secret, encoded_body['client_secret'][0]) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_issue_link_token.py b/tests/api/test_issue_link_token.py deleted file mode 100644 index 90517e0f7..000000000 --- a/tests/api/test_issue_link_token.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - @responses.activate - def test_issue_line_token(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/user_id/linkToken', - json={ - "linkToken": "xxxx", - }, - status=200 - ) - - issue_link_token_response = self.tested.issue_link_token('user_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/user_id/linkToken') - self.assertEqual(issue_link_token_response.link_token, 'xxxx') - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_issue_stateless_channel_token.py b/tests/api/test_issue_stateless_channel_token.py deleted file mode 100644 index aeabfc8c7..000000000 --- a/tests/api/test_issue_stateless_channel_token.py +++ /dev/null @@ -1,192 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import unittest -from urllib.parse import parse_qs - -from pytest_httpserver import HTTPServer -from linebot.v3.oauth import ( - Configuration, - ApiClient, - ChannelAccessToken, -) - - -class TestIssueStatelessChannelToken(unittest.TestCase): - - def test_issue_stateless_channel_token_by_jwt_assertion(self): - client_assertion = 'eyJhbGciOiJSUzI.q....' - client_assertion_type = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer' - - with HTTPServer() as httpserver: - httpserver.expect_request( - uri="/oauth2/v3/token", - method="POST", - ).respond_with_json( - { - 'access_token': 'test_access_token', - 'expires_in': 900, - 'token_type': 'Bearer', - }, - status=200, - ) - - configuration = Configuration(host=httpserver.url_for("/")) - with ApiClient(configuration) as api_client: - api = ChannelAccessToken(api_client) - api.line_base_path = httpserver.url_for("/") - - response = api.issue_stateless_channel_token_by_jwt_assertion( - client_assertion, - ) - - self.assertEqual(response.access_token, 'test_access_token') - self.assertEqual(response.expires_in, 900) - self.assertEqual(response.token_type, 'Bearer') - self.assertEqual(len(httpserver.log), 1) - - request, _ = httpserver.log[0] - encoded_body = parse_qs(request.data.decode('utf-8')) - self.assertEqual(encoded_body['grant_type'], ['client_credentials']) - self.assertEqual(encoded_body['client_assertion_type'], [client_assertion_type]) - self.assertEqual(encoded_body['client_assertion'], [client_assertion]) - self.assertNotIn('client_id', encoded_body) - self.assertNotIn('client_secret', encoded_body) - - def test_issue_stateless_channel_token_by_client_secret(self): - client_id = 'test_client_id' - client_secret = 'test_client_secret' - - with HTTPServer() as httpserver: - httpserver.expect_request( - uri="/oauth2/v3/token", - method="POST", - ).respond_with_json( - { - 'access_token': 'test_access_token', - 'expires_in': 900, - 'token_type': 'Bearer', - }, - status=200, - ) - - configuration = Configuration(host=httpserver.url_for("/")) - with ApiClient(configuration) as api_client: - api = ChannelAccessToken(api_client) - api.line_base_path = httpserver.url_for("/") - - response = api.issue_stateless_channel_token_by_client_secret( - client_id, - client_secret, - ) - - self.assertEqual(response.access_token, 'test_access_token') - self.assertEqual(response.expires_in, 900) - self.assertEqual(response.token_type, 'Bearer') - self.assertEqual(len(httpserver.log), 1) - - request, _ = httpserver.log[0] - encoded_body = parse_qs(request.data.decode('utf-8')) - self.assertEqual(encoded_body['grant_type'], ['client_credentials']) - self.assertEqual(encoded_body['client_id'], [client_id]) - self.assertEqual(encoded_body['client_secret'], [client_secret]) - self.assertNotIn('client_assertion_type', encoded_body) - self.assertNotIn('client_assertion', encoded_body) - - def test_issue_stateless_channel_token_with_http_info_by_jwt_assertion(self): - client_assertion = 'eyJhbGciOiJSUzI.q....' - client_assertion_type = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer' - - with HTTPServer() as httpserver: - httpserver.expect_request( - uri="/oauth2/v3/token", - method="POST", - ).respond_with_json( - { - 'access_token': 'test_access_token', - 'expires_in': 900, - 'token_type': 'Bearer', - }, - status=200, - ) - - configuration = Configuration(host=httpserver.url_for("/")) - with ApiClient(configuration) as api_client: - api = ChannelAccessToken(api_client) - api.line_base_path = httpserver.url_for("/") - - api_response = api.issue_stateless_channel_token_with_http_info_by_jwt_assertion( - client_assertion, - ) - - self.assertEqual(api_response.status_code, 200) - response = api_response.data - self.assertEqual(response.access_token, 'test_access_token') - self.assertEqual(response.expires_in, 900) - self.assertEqual(response.token_type, 'Bearer') - self.assertEqual(len(httpserver.log), 1) - - request, _ = httpserver.log[0] - encoded_body = parse_qs(request.data.decode('utf-8')) - self.assertEqual(encoded_body['grant_type'], ['client_credentials']) - self.assertEqual(encoded_body['client_assertion_type'], [client_assertion_type]) - self.assertEqual(encoded_body['client_assertion'], [client_assertion]) - self.assertNotIn('client_id', encoded_body) - self.assertNotIn('client_secret', encoded_body) - - def test_issue_stateless_channel_token_with_http_info_by_client_secret(self): - client_id = 'test_client_id' - client_secret = 'test_client_secret' - - with HTTPServer() as httpserver: - httpserver.expect_request( - uri="/oauth2/v3/token", - method="POST", - ).respond_with_json( - { - 'access_token': 'test_access_token', - 'expires_in': 900, - 'token_type': 'Bearer', - }, - status=200, - ) - - configuration = Configuration(host=httpserver.url_for("/")) - with ApiClient(configuration) as api_client: - api = ChannelAccessToken(api_client) - api.line_base_path = httpserver.url_for("/") - - api_response = api.issue_stateless_channel_token_with_http_info_by_client_secret( - client_id, - client_secret, - ) - - self.assertEqual(api_response.status_code, 200) - response = api_response.data - self.assertEqual(response.access_token, 'test_access_token') - self.assertEqual(response.expires_in, 900) - self.assertEqual(response.token_type, 'Bearer') - self.assertEqual(len(httpserver.log), 1) - - request, _ = httpserver.log[0] - encoded_body = parse_qs(request.data.decode('utf-8')) - self.assertEqual(encoded_body['grant_type'], ['client_credentials']) - self.assertEqual(encoded_body['client_id'], [client_id]) - self.assertEqual(encoded_body['client_secret'], [client_secret]) - self.assertNotIn('client_assertion_type', encoded_body) - self.assertNotIn('client_assertion', encoded_body) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_leave.py b/tests/api/test_leave.py deleted file mode 100644 index 7322f9d72..000000000 --- a/tests/api/test_leave.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - @responses.activate - def test_leave_group(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/gid/leave', - json={}, status=200 - ) - - self.tested.leave_group('gid') - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/group/gid/leave') - - @responses.activate - def test_leave_room(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/room/rid/leave', - json={}, status=200 - ) - - self.tested.leave_room('rid') - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/room/rid/leave') - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_narrowcast_message.py b/tests/api/test_narrowcast_message.py deleted file mode 100644 index 99417cc1c..000000000 --- a/tests/api/test_narrowcast_message.py +++ /dev/null @@ -1,422 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - TextSendMessage, - Limit, - And, - Or, - Not, - Filter, - GenderFilter, - AppTypeFilter, - AreaFilter, - AgeFilter, - AudienceRecipient, - SubscriptionPeriodFilter, - RedeliveryRecipient, -) - - -class TestNarrowcastMessage(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - self.maxDiff = None - self.request_id = 'f70dd685-499a-4231-a441-f24b8d4fba21' - - # test data - self.text_message = TextSendMessage(text='Hello, world') - self.message = [{"type": "text", "text": "Hello, world"}] - - @responses.activate - def test_narrowcast_simple_text_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/narrowcast', - json={}, status=200, - headers={'X-Line-Request-Id': 'request_id_test'}, - ) - - self.tested.narrowcast( - self.text_message, - recipient=AudienceRecipient(group_id=5614991017776), - filter=Filter(demographic=AgeFilter(gte="age_35", lt="age_40")), - limit=Limit(max=10), - ) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/narrowcast') - self.assertEqual(request.method, 'POST') - self.assertEqual( - json.loads(request.body), - { - "messages": self.message, - "recipient": { - 'audienceGroupId': 5614991017776, - 'type': 'audience' - }, - "filter": { - "demographic": { - "type": "age", - "gte": "age_35", - "lt": "age_40" - } - }, - "limit": { - "max": 10, - "upToRemainingQuota": False, - }, - "notificationDisabled": False, - } - ) - - @responses.activate - def test_narrowcast_redelivery_recipient_text_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/narrowcast', - json={}, status=200, - ) - - self.tested.narrowcast( - self.text_message, - recipient=And( - AudienceRecipient(group_id=5614991017776), - Not( - RedeliveryRecipient(request_id='request_id_test') - ) - ), - filter=Filter(demographic=AgeFilter(gte="age_35", lt="age_40")), - limit=Limit(max=10), - ) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/narrowcast') - self.assertEqual(request.method, 'POST') - self.assertEqual( - json.loads(request.body), - { - "messages": self.message, - "recipient": { - "type": "operator", - "and": [ - { - "type": "audience", - "audienceGroupId": 5614991017776 - }, - { - "type": "operator", - "not": { - "type": "redelivery", - "requestId": "request_id_test" - } - } - ] - }, - "filter": { - "demographic": { - "type": "age", - "gte": "age_35", - "lt": "age_40" - } - }, - "limit": { - "max": 10, - "upToRemainingQuota": False, - }, - "notificationDisabled": False, - } - ) - - @responses.activate - def test_narrowcast_text_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/narrowcast', - json={}, status=200, - headers={'X-Line-Request-Id': 'request_id_test'}, - ) - - response = self.tested.narrowcast( - self.text_message, - recipient=And( - AudienceRecipient(group_id=5614991017776), - Not(AudienceRecipient(group_id=4389303728991)) - ), - filter=Filter( - demographic=Or( - And( - GenderFilter(one_of=["male", "female"]), - AgeFilter(gte="age_20", lt="age_25"), - AppTypeFilter(one_of=["android", "ios"]), - AreaFilter(one_of=["jp_23", "jp_05"]), - SubscriptionPeriodFilter(gte="day_7", lt="day_30") - ), - And( - AgeFilter(gte="age_35", lt="age_40"), - Not(GenderFilter(one_of=["male"])) - ) - ) - ), - limit=Limit(max=100, up_to_remaining_quota=True), - ) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/narrowcast') - self.assertEqual(request.method, 'POST') - self.assertEqual( - json.loads(request.body), - { - "messages": self.message, - "recipient": { - "type": "operator", - "and": [ - { - 'audienceGroupId': 5614991017776, - 'type': 'audience' - }, - { - "type": "operator", - "not": { - "type": "audience", - "audienceGroupId": 4389303728991 - } - } - ] - }, - "filter": { - "demographic": { - "type": "operator", - "or": [ - { - "type": "operator", - "and": [ - { - "type": "gender", - "oneOf": [ - "male", - "female" - ] - }, - { - "type": "age", - "gte": "age_20", - "lt": "age_25" - }, - { - "type": "appType", - "oneOf": [ - "android", - "ios" - ] - }, - { - "type": "area", - "oneOf": [ - "jp_23", - "jp_05" - ] - }, - { - "type": "subscriptionPeriod", - "gte": "day_7", - "lt": "day_30" - } - ] - }, - { - "type": "operator", - "and": [ - { - "type": "age", - "gte": "age_35", - "lt": "age_40" - }, - { - "type": "operator", - "not": { - "type": "gender", - "oneOf": [ - "male" - ] - } - } - ] - } - ] - } - }, - "limit": { - "max": 100, - "upToRemainingQuota": True, - }, - "notificationDisabled": False, - } - ) - self.assertEqual('request_id_test', response.request_id) - - @responses.activate - def test_narrowcast_text_message_with_retry_key(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/narrowcast', - json={}, status=200, - headers={ - 'X-Line-Request-Id': 'request_id_test', - 'X-Line-Retry-Key': '123e4567-e89b-12d3-a456-426614174000' - }, - ) - - response = self.tested.narrowcast( - self.text_message, - recipient=And( - AudienceRecipient(group_id=5614991017776), - Not(AudienceRecipient(group_id=4389303728991)) - ), - filter=Filter( - demographic=Or( - And( - GenderFilter(one_of=["male", "female"]) - ) - ) - ), - limit=Limit(max=100, up_to_remaining_quota=True), - retry_key='123e4567-e89b-12d3-a456-426614174000', - ) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/narrowcast') - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.headers['X-Line-Retry-Key'], - '123e4567-e89b-12d3-a456-426614174000' - ) - self.assertEqual( - json.loads(request.body), - { - "messages": self.message, - "recipient": { - "type": "operator", - "and": [ - { - 'audienceGroupId': 5614991017776, - 'type': 'audience' - }, - { - "type": "operator", - "not": { - "type": "audience", - "audienceGroupId": 4389303728991 - } - } - ] - }, - "filter": { - "demographic": { - "type": "operator", - "or": [ - { - "type": "operator", - "and": [ - { - "type": "gender", - "oneOf": [ - "male", - "female" - ] - } - ] - } - ] - } - }, - "limit": { - "max": 100, - "upToRemainingQuota": True, - }, - "notificationDisabled": False, - } - ) - self.assertEqual('request_id_test', response.request_id) - - @responses.activate - def test_get_progress_status_narrowcast(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/message/progress/narrowcast?requestId={request_id}'.format( - request_id=self.request_id), - json={'phase': 'waiting'}, status=200, - ) - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/message/progress/narrowcast?requestId={request_id}'.format( - request_id=self.request_id), - json={ - 'phase': 'succeeded', - 'successCount': 10, - 'failureCount': 0, - 'targetCount': 10, - }, status=200, - ) - - res = self.tested.get_progress_status_narrowcast(self.request_id) - request = responses.calls[0].request - self.assertEqual('GET', request.method) - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/message/progress/narrowcast?requestId={request_id}'.format( - request_id=self.request_id) - ) - - self.assertEqual(res.phase, 'waiting') - - res = self.tested.get_progress_status_narrowcast(self.request_id) - request = responses.calls[1].request - self.assertEqual('GET', request.method) - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/message/progress/narrowcast?requestId={request_id}'.format( - request_id=self.request_id) - ) - - self.assertEqual(res.phase, 'succeeded') - self.assertEqual(res.success_count, 10) - self.assertEqual(res.failure_count, 0) - self.assertEqual(res.target_count, 10) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_revoke_channel_token.py b/tests/api/test_revoke_channel_token.py deleted file mode 100644 index 64543cef6..000000000 --- a/tests/api/test_revoke_channel_token.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - self.endpoint = LineBotApi.DEFAULT_API_ENDPOINT + '/v2/oauth/revoke' - self.access_token = "W1TeHCgfH2Liwa....." - - @responses.activate - def test_issue_line_token(self): - responses.add( - responses.POST, - self.endpoint, - status=200 - ) - - self.tested.revoke_channel_token(self.access_token) - - request = responses.calls[0].request - self.assertEqual('POST', request.method) - self.assertEqual(self.endpoint, request.url) - self.assertEqual('application/x-www-form-urlencoded', request.headers['content-type']) - self.assertEqual('access_token={}'.format(self.access_token), request.body) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_rich_menu.py b/tests/api/test_rich_menu.py deleted file mode 100644 index 9147c1a69..000000000 --- a/tests/api/test_rich_menu.py +++ /dev/null @@ -1,551 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - URITemplateAction, - RichMenu, RichMenuSize, RichMenuArea, RichMenuBounds -) -from linebot.models.actions import RichMenuSwitchAction - - -class TestLineBotApi(unittest.TestCase): - maxDiff = None - - def setUp(self): - self.tested = LineBotApi('channel_secret') - - self.rich_menu_id = 'richmenu-0000000000' - self.user_id = 'userid' - self.rich_menu = RichMenu( - size=RichMenuSize( - width=2500, - height=1686 - ), - selected=False, - name="nice richmenu", - chatBarText="touch me", - areas=[ - RichMenuArea( - RichMenuBounds( - x=0, - y=0, - width=833, - height=843 - ), - URITemplateAction( - uri='https://line.me/R/nv/location/' - ) - ) - ] - ) - - @responses.activate - def test_get_rich_menu(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/rich_menu_id', - json={ - "richMenuId": "rich_menu_id", - "size": { - "width": 2500, - "height": 1686 - }, - "selected": False, - "name": "name", - "chatBarText": "chatBarText", - "areas": [ - { - "bounds": { - "x": 0, - "y": 0, - "width": 2500, - "height": 1686 - }, - "action": { - "type": "postback", - "data": "action=buy&itemid=123" - } - } - ] - }, - status=200 - ) - - rich_menu = self.tested.get_rich_menu('rich_menu_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/rich_menu_id' - ) - - self.assertEqual(rich_menu.rich_menu_id, 'rich_menu_id') - self.assertEqual(rich_menu.size.width, 2500) - self.assertEqual(rich_menu.size.height, 1686) - self.assertEqual(rich_menu.selected, False) - self.assertEqual(rich_menu.name, 'name') - self.assertEqual(rich_menu.chat_bar_text, 'chatBarText') - self.assertEqual(rich_menu.areas[0].bounds.x, 0) - self.assertEqual(rich_menu.areas[0].bounds.y, 0) - self.assertEqual(rich_menu.areas[0].bounds.width, 2500) - self.assertEqual(rich_menu.areas[0].bounds.height, 1686) - self.assertEqual(rich_menu.areas[0].action.type, 'postback') - self.assertEqual(rich_menu.areas[0].action.data, 'action=buy&itemid=123') - - @responses.activate - def test_validate_rich_menu_object(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/validate', - json={}, status=200 - ) - - rich_menu = RichMenu( - size=RichMenuSize( - width=2500, - height=1686 - ), - selected=False, - name="nice richmenu", - chatBarText="touch me", - areas=[ - RichMenuArea( - RichMenuBounds( - x=0, - y=0, - width=833, - height=843 - ), - URITemplateAction( - uri='https://line.me/R/nv/location/' - ) - ) - ] - ) - - self.tested.validate_rich_menu_object(rich_menu) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/validate' - ) - - @responses.activate - def test_create_rich_menu(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu', - json={"richMenuId": "richMenuId"}, status=200 - ) - - rich_menu = RichMenu( - size=RichMenuSize( - width=2500, - height=1686 - ), - selected=False, - name="nice richmenu", - chatBarText="touch me", - areas=[ - RichMenuArea( - RichMenuBounds( - x=0, - y=0, - width=833, - height=843 - ), - URITemplateAction( - uri='https://line.me/R/nv/location/' - ) - ) - ] - ) - - result = self.tested.create_rich_menu(rich_menu) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu' - ) - self.assertEqual(result, "richMenuId") - - @responses.activate - def test_delete_rich_menu(self): - responses.add( - responses.DELETE, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/rich_menu_id', - json={}, status=200 - ) - - self.tested.delete_rich_menu('rich_menu_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'DELETE') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/rich_menu_id' - ) - - @responses.activate - def test_get_rich_menu_id_of_user(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/user/user_id/richmenu', - json={"richMenuId": "richMenuId"}, status=200 - ) - - result = self.tested.get_rich_menu_id_of_user('user_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/user_id/richmenu' - ) - self.assertEqual(result, "richMenuId") - - @responses.activate - def test_link_rich_menu_to_user(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/user/user_id/richmenu/rich_menu_id', - json={}, status=200 - ) - - self.tested.link_rich_menu_to_user('user_id', 'rich_menu_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/user_id/richmenu/rich_menu_id' - ) - - @responses.activate - def test_unlink_rich_menu_from_user(self): - responses.add( - responses.DELETE, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/user/user_id/richmenu', - json={}, status=200 - ) - - self.tested.unlink_rich_menu_from_user('user_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'DELETE') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/user_id/richmenu' - ) - - @responses.activate - def test_get_rich_menu_list(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/list', - json={ - "richmenus": [ - { - "richMenuId": "rich_menu_id", - "size": { - "width": 2500, - "height": 1686 - }, - "selected": False, - "name": "name", - "chatBarText": "chatBarText", - "areas": [ - { - "bounds": { - "x": 0, - "y": 0, - "width": 2500, - "height": 1686 - }, - "action": { - "type": "postback", - "data": "action=buy&itemid=123" - } - } - ] - } - ] - }, - status=200 - ) - - rich_menus = self.tested.get_rich_menu_list() - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/list' - ) - self.assertEqual(rich_menus[0].rich_menu_id, 'rich_menu_id') - self.assertEqual(rich_menus[0].size.width, 2500) - self.assertEqual(rich_menus[0].size.height, 1686) - self.assertEqual(rich_menus[0].selected, False) - self.assertEqual(rich_menus[0].name, 'name') - self.assertEqual(rich_menus[0].chat_bar_text, 'chatBarText') - self.assertEqual(rich_menus[0].areas[0].bounds.x, 0) - self.assertEqual(rich_menus[0].areas[0].bounds.y, 0) - self.assertEqual(rich_menus[0].areas[0].bounds.width, 2500) - self.assertEqual(rich_menus[0].areas[0].bounds.height, 1686) - self.assertEqual(rich_menus[0].areas[0].action.type, 'postback') - self.assertEqual(rich_menus[0].areas[0].action.data, 'action=buy&itemid=123') - - @responses.activate - def test_link_rich_menu_to_users(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/richmenu/bulk/link', - json={}, status=202 - ) - - self.tested.link_rich_menu_to_users(['user_id1', 'user_id2'], 'rich_menu_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/bulk/link' - ) - self.assertEqual( - json.loads(request.body), - { - "richMenuId": "rich_menu_id", - "userIds": ["user_id1", "user_id2"], - } - ) - - @responses.activate - def test_unlink_rich_menu_to_users(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/richmenu/bulk/unlink', - json={}, status=202 - ) - - self.tested.unlink_rich_menu_from_users(['user_id1', 'user_id2'], 'rich_menu_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/bulk/unlink' - ) - self.assertEqual( - json.loads(request.body), - { - "userIds": ["user_id1", "user_id2"], - } - ) - - @responses.activate - def test_set_default_rich_menu(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/user/all/richmenu/rich_menu_id', - json={}, status=200 - ) - - self.tested.set_default_rich_menu('rich_menu_id') - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/all/richmenu/rich_menu_id' - ) - - @responses.activate - def test_get_default_rich_menu(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/user/all/richmenu', - json={"richMenuId": "richMenuId"}, status=200 - ) - - result = self.tested.get_default_rich_menu() - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/all/richmenu' - ) - self.assertEqual(result, "richMenuId") - - @responses.activate - def test_cancel_default_rich_menu(self): - responses.add( - responses.DELETE, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/user/all/richmenu', - json={}, status=200 - ) - - self.tested.cancel_default_rich_menu() - - request = responses.calls[0].request - self.assertEqual(request.method, 'DELETE') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/user/all/richmenu' - ) - - @responses.activate - def test_get_rich_menu_image(self): - rich_menu_id = '1234' - body = b'hogieoidksk' - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_DATA_ENDPOINT + - '/v2/bot/richmenu/{rich_menu_id}/content'.format(rich_menu_id=rich_menu_id), - body=body, status=200 - ) - - res = self.tested.get_rich_menu_image(rich_menu_id) - - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_DATA_ENDPOINT + - '/v2/bot/richmenu/{rich_menu_id}/content'.format(rich_menu_id=rich_menu_id), - ) - self.assertEqual( - body, - res.content - ) - - @responses.activate - def test_set_rich_menu_image(self): - rich_menu_id = '1234' - body = b'hogieoidksk' - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_DATA_ENDPOINT + - '/v2/bot/richmenu/{rich_menu_id}/content'.format(rich_menu_id=rich_menu_id), - json={}, status=200 - ) - - self.tested.set_rich_menu_image( - rich_menu_id=rich_menu_id, - content_type='image/jpeg', - content=body - ) - - request = responses.calls[0].request - self.assertEqual('POST', request.method) - self.assertEqual( - LineBotApi.DEFAULT_API_DATA_ENDPOINT + - '/v2/bot/richmenu/{rich_menu_id}/content'.format(rich_menu_id=rich_menu_id), - request.url - ) - - @responses.activate - def test_rich_menu_with_switch_action(self): - rich_menu = RichMenu( - size=RichMenuSize( - width=2500, - height=1686 - ), - selected=False, - name="nice richmenu", - chatBarText="touch me", - areas=[ - RichMenuArea( - RichMenuBounds( - x=0, - y=0, - width=833, - height=843 - ), - RichMenuSwitchAction( - rich_menu_alias_id="richmenu-alias-a", - data="richmenu-changed-to-a" - ) - ) - ] - ) - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu', - json={ - "richMenuId": "rich_menu_id", - "size": { - "width": 2500, - "height": 1686 - }, - "selected": False, - "name": "name", - "chatBarText": "chatBarText", - "areas": [ - { - "bounds": { - "x": 0, - "y": 0, - "width": 2500, - "height": 1686 - }, - "action": { - "type": "richmenuswitch", - "richMenuAliasId": "richmenu-alias-a", - "data": "richmenu-changed-to-a" - } - } - ] - }, - status=200 - ) - - result = self.tested.create_rich_menu(rich_menu) - print(rich_menu) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu' - ) - - self.assertEqual(result, "rich_menu_id") - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_rich_menu_alias.py b/tests/api/test_rich_menu_alias.py deleted file mode 100644 index 6c57748a3..000000000 --- a/tests/api/test_rich_menu_alias.py +++ /dev/null @@ -1,178 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest -import responses - -from linebot import ( - LineBotApi -) -from linebot.models.rich_menu import RichMenuAlias - - -class TestLineBotApi(unittest.TestCase): - maxDiff = None - - def setUp(self): - self.tested = LineBotApi('channel_secret') - - self.alias_id_a = 'richmenu-alias-a' - self.alias_id_b = 'richmenu-alias-b' - self.rich_menu_id_a = 'richmenu-0000000' - self.rich_menu_id_b = 'richmenu-1111111' - - @responses.activate - def test_create_rich_menu_alias(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/alias', - json={ - "richMenuAliasId": self.alias_id_a, - "richMenuId": self.rich_menu_id_a - }, status=200 - ) - alias = RichMenuAlias( - rich_menu_alias_id=self.alias_id_a, - rich_menu_id=self.rich_menu_id_a - ) - result = self.tested.create_rich_menu_alias(alias) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/alias' - ) - self.assertEqual(result, None) - - @responses.activate - def test_delete_rich_menu(self): - responses.add( - responses.DELETE, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/alias/' + self.alias_id_a, - json={}, status=200 - ) - - result = self.tested.delete_rich_menu_alias(self.alias_id_a) - - request = responses.calls[0].request - self.assertEqual(request.method, 'DELETE') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/alias/richmenu-alias-a' - ) - self.assertEqual(result, None) - - @responses.activate - def test_update_rich_menu_alias(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/alias/' + self.alias_id_a, - json={}, status=200 - ) - - alias = RichMenuAlias(rich_menu_id=self.rich_menu_id_a) - result = self.tested.update_rich_menu_alias( - rich_menu_alias_id=self.alias_id_a, rich_menu_alias=alias - ) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/alias/richmenu-alias-a' - ) - self.assertEqual(result, None) - - @responses.activate - def test_get_rich_menu_alias(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/richmenu/alias/' + self.alias_id_a, - json={ - "richMenuAliasId": self.alias_id_a, - "richMenuId": self.rich_menu_id_a - }, status=200 - ) - - result = self.tested.get_rich_menu_alias(rich_menu_alias_id=self.alias_id_a) - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/alias/richmenu-alias-a' - ) - self.assertEqual(result.rich_menu_alias_id, 'richmenu-alias-a') - self.assertEqual(result.rich_menu_id, 'richmenu-0000000') - - @responses.activate - def test_get_rich_menu_alias_list(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/richmenu/alias/list', - json={ - "aliases": [{ - "richMenuAliasId": self.alias_id_a, - "richMenuId": self.rich_menu_id_a - }, { - "richMenuAliasId": self.alias_id_b, - "richMenuId": self.rich_menu_id_b - }] - }, status=200 - ) - - result = self.tested.get_rich_menu_alias_list() - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/alias/list' - ) - self.assertEqual(type(result.aliases), list) - self.assertEqual(result.aliases[0].rich_menu_alias_id, "richmenu-alias-a") - self.assertEqual( - result.aliases[0].rich_menu_id, "richmenu-0000000" - ) - self.assertEqual(result.aliases[1].rich_menu_alias_id, "richmenu-alias-b") - self.assertEqual( - result.aliases[1].rich_menu_id, "richmenu-1111111" - ) - - @responses.activate - def test_get_rich_menu_alias_empty_list(self): - responses.add( - responses.GET, - LineBotApi.DEFAULT_API_ENDPOINT + - '/v2/bot/richmenu/alias/list', - json={"aliases": []}, - status=200 - ) - - result = self.tested.get_rich_menu_alias_list() - request = responses.calls[0].request - self.assertEqual(request.method, 'GET') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/richmenu/alias/list' - ) - self.assertEqual(type(result.aliases), list) - self.assertEqual(len(result.aliases), 0) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_send_audio_message.py b/tests/api/test_send_audio_message.py deleted file mode 100644 index 24888a32f..000000000 --- a/tests/api/test_send_audio_message.py +++ /dev/null @@ -1,120 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - AudioSendMessage -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - self.audio_message = AudioSendMessage( - original_content_url='https://example.com/original.m4a', - duration=240000 - ) - - self.message = [{ - "type": "audio", - "originalContentUrl": "https://example.com/original.m4a", - "duration": 240000, - }] - - @responses.activate - def test_push_audio_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', self.audio_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push' - ) - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_reply_audio_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', - json={}, status=200 - ) - - self.tested.reply_message('replyToken', self.audio_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') - self.assertEqual( - json.loads(request.body), - { - "replyToken": "replyToken", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_multicast_audio_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', - json={}, status=200 - ) - - self.tested.multicast(['to1', 'to2'], self.audio_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') - self.assertEqual( - json.loads(request.body), - { - "to": ['to1', 'to2'], - 'notificationDisabled': False, - "messages": self.message - } - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_send_image_message.py b/tests/api/test_send_image_message.py deleted file mode 100644 index 1b59e3f46..000000000 --- a/tests/api/test_send_image_message.py +++ /dev/null @@ -1,119 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - ImageSendMessage -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - self.image_message = ImageSendMessage( - original_content_url='https://example.com/original.jpg', - preview_image_url='https://example.com/preview.jpg' - ) - - self.message = [{ - "type": "image", - "originalContentUrl": "https://example.com/original.jpg", - "previewImageUrl": "https://example.com/preview.jpg", - }] - - @responses.activate - def test_push_image_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', self.image_message) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual(request.method, 'POST') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_reply_image_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', - json={}, status=200 - ) - - self.tested.reply_message('replyToken', self.image_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') - self.assertEqual( - json.loads(request.body), - { - "replyToken": "replyToken", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_multicast_image_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', - json={}, status=200 - ) - - self.tested.multicast(['to1', 'to2'], self.image_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') - self.assertEqual( - json.loads(request.body), - { - "to": ['to1', 'to2'], - 'notificationDisabled': False, - "messages": self.message - } - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_send_imagemap_message.py b/tests/api/test_send_imagemap_message.py deleted file mode 100644 index bbac91d39..000000000 --- a/tests/api/test_send_imagemap_message.py +++ /dev/null @@ -1,187 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - ImagemapSendMessage, BaseSize, URIImagemapAction, - ImagemapArea, MessageImagemapAction, - Video, ExternalLink -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - self.imagemap_message = ImagemapSendMessage( - base_url='https://example.com/base', - alt_text='this is an imagemap', - base_size=BaseSize(height=1040, width=1040), - video=Video( - original_content_url='https://example.com/video.mp4', - preview_image_url='https://example.com/video_preview.jpg', - area=ImagemapArea( - x=0, y=0, width=1040, height=585 - ), - external_link=ExternalLink( - link_uri='https://example.com/see_more.html', - label='See More', - ), - ), - actions=[ - URIImagemapAction( - link_uri='https://example.com/', - area=ImagemapArea( - x=0, y=0, width=520, height=1040 - ) - ), - MessageImagemapAction( - text='hello', - area=ImagemapArea( - x=520, y=0, width=520, height=1040 - ) - ) - ] - ) - - self.message = [{ - "type": "imagemap", - "baseUrl": "https://example.com/base", - "altText": "this is an imagemap", - "baseSize": { - "height": 1040, - "width": 1040 - }, - "video": { - "originalContentUrl": "https://example.com/video.mp4", - "previewImageUrl": "https://example.com/video_preview.jpg", - "area": { - "x": 0, - "y": 0, - "width": 1040, - "height": 585 - }, - "externalLink": { - "linkUri": "https://example.com/see_more.html", - "label": "See More" - } - }, - "actions": [ - { - "type": "uri", - "linkUri": "https://example.com/", - "area": { - "x": 0, - "y": 0, - "width": 520, - "height": 1040 - } - }, - { - "type": "message", - "text": "hello", - "area": { - "x": 520, - "y": 0, - "width": 520, - "height": 1040 - } - } - ] - }] - - @responses.activate - def test_push_imagemap_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', self.imagemap_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_reply_imagemap_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', - json={}, status=200 - ) - - self.tested.reply_message('replyToken', self.imagemap_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') - self.assertEqual( - json.loads(request.body), - { - "replyToken": "replyToken", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_multicast_imagemap_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', - json={}, status=200 - ) - - self.tested.multicast(['to1', 'to2'], self.imagemap_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') - self.assertEqual( - json.loads(request.body), - { - "to": ['to1', 'to2'], - 'notificationDisabled': False, - "messages": self.message - } - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_send_location_message.py b/tests/api/test_send_location_message.py deleted file mode 100644 index c7f5d0c54..000000000 --- a/tests/api/test_send_location_message.py +++ /dev/null @@ -1,123 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - LocationSendMessage -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - self.location_message = LocationSendMessage( - title='my location', - address='Tokyo', - latitude=35.65910807942215, - longitude=139.70372892916203 - ) - - self.message = [{ - "type": "location", - "title": "my location", - "address": "Tokyo", - "latitude": 35.65910807942215, - "longitude": 139.70372892916203 - }] - - @responses.activate - def test_push_location_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', self.location_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_reply_location_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', - json={}, status=200 - ) - - self.tested.reply_message('replyToken', self.location_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') - self.assertEqual( - json.loads(request.body), - { - "replyToken": "replyToken", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_multicast_location_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', - json={}, status=200 - ) - - self.tested.multicast(['to1', 'to2'], self.location_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') - self.assertEqual( - json.loads(request.body), - { - "to": ['to1', 'to2'], - 'notificationDisabled': False, - "messages": self.message - } - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_send_sticker_message.py b/tests/api/test_send_sticker_message.py deleted file mode 100644 index 323d9aae1..000000000 --- a/tests/api/test_send_sticker_message.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - StickerSendMessage -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - self.sticker_message = StickerSendMessage( - package_id='1', sticker_id='1' - ) - - self.message = [{ - "type": "sticker", - "packageId": "1", - "stickerId": "1" - }] - - @responses.activate - def test_push_sticker_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', self.sticker_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_reply_sticker_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', - json={}, status=200 - ) - - self.tested.reply_message('replyToken', self.sticker_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') - self.assertEqual( - json.loads(request.body), - { - "replyToken": "replyToken", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_multicast_sticker_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', - json={}, status=200 - ) - - self.tested.multicast(['to1', 'to2'], self.sticker_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') - self.assertEqual( - json.loads(request.body), - { - "to": ['to1', 'to2'], - 'notificationDisabled': False, - "messages": self.message - } - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_send_template_message.py b/tests/api/test_send_template_message.py deleted file mode 100644 index a6ab7ab71..000000000 --- a/tests/api/test_send_template_message.py +++ /dev/null @@ -1,611 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - TemplateSendMessage, ButtonsTemplate, - PostbackAction, MessageAction, - URIAction, AltUri, DatetimePickerAction, - ConfirmTemplate, CarouselTemplate, CarouselColumn, - ImageCarouselTemplate, ImageCarouselColumn -) - - -class TestLineBotApi(unittest.TestCase): - maxDiff = None - - def setUp(self): - self.tested = LineBotApi('channel_secret') - - self.button_template_message = TemplateSendMessage( - alt_text='Buttons template', - template=ButtonsTemplate( - thumbnail_image_url='https://example.com/image.jpg', - title='Menu', text='Please select', - actions=[ - PostbackAction( - label='postback', display_text='postback text', - data='action=buy&itemid=1' - ), - MessageAction( - label='message', text='message text' - ), - URIAction( - label='uri', uri='http://example.com/', - alt_uri=AltUri(desktop="http://example.com/desktop") - ) - ] - ) - ) - - self.button_message = [{ - "type": "template", - "altText": "Buttons template", - "template": { - "type": "buttons", - "thumbnailImageUrl": - "https://example.com/image.jpg", - "title": "Menu", - "text": "Please select", - "actions": [ - { - "type": "postback", - "label": "postback", - "displayText": "postback text", - "data": "action=buy&itemid=1" - }, - { - "type": "message", - "label": "message", - "text": "message text" - }, - { - "type": "uri", - "label": "uri", - "uri": "http://example.com/", - "altUri": { - "desktop": "http://example.com/desktop" - } - } - ] - } - }] - - self.confirm_template_message = TemplateSendMessage( - alt_text='Confirm template', - template=ConfirmTemplate( - text='Are you sure?', - actions=[ - PostbackAction( - label='postback', display_text='postback text', - data='action=buy&itemid=1' - ), - MessageAction( - label='message', text='message text' - ) - ] - ) - ) - - self.confirm_message = [{ - "type": "template", - "altText": "Confirm template", - "template": { - "type": "confirm", - "text": "Are you sure?", - "actions": [ - { - "type": "postback", - "label": "postback", - "displayText": "postback text", - "data": "action=buy&itemid=1" - }, - { - "type": "message", - "label": "message", - "text": "message text" - } - ] - } - }] - - self.carousel_template_message = TemplateSendMessage( - alt_text='Carousel template', - template=CarouselTemplate( - columns=[ - CarouselColumn( - thumbnail_image_url='https://example.com' - '/item1.jpg', - title='this is menu1', text='description1', - actions=[ - PostbackAction( - label='postback1', display_text='postback text1', - data='action=buy&itemid=1' - ), - MessageAction( - label='message1', text='message text1' - ), - URIAction( - label='uri1', - uri='http://example.com/1' - ) - ] - ), - CarouselColumn( - thumbnail_image_url='https://example.com' - '/item2.jpg', - image_background_color='#000000', - title='this is menu2', text='description2', - actions=[ - PostbackAction( - label='postback2', display_text='postback text2', - data='action=buy&itemid=2' - ), - MessageAction( - label='message2', text='message text2' - ), - URIAction( - label='uri2', - uri='http://example.com/2' - ) - ] - ), - CarouselColumn( - thumbnail_image_url='https://example.com' - '/item3.jpg', - title='this is menu3', text='description3', - actions=[ - DatetimePickerAction( - label="datetime picker date", - data="action=sell&itemid=2&mode=date", - mode="date", - initial="2013-04-01", - min="2011-06-23", - max="2017-09-08" - ), - DatetimePickerAction( - label="datetime picker time", - data="action=sell&itemid=2&mode=time", - mode="time", - initial="10:00", - min="00:00", - max="23:59" - ), - DatetimePickerAction( - label="datetime picker datetime", - data="action=sell&itemid=2&mode=datetime", - mode="datetime", - initial="2013-04-01T10:00", - min="2011-06-23T00:00", - max="2017-09-08T23:59" - ) - ] - ) - ] - ) - ) - - self.carousel_message = [{ - "type": "template", - "altText": "Carousel template", - "template": { - "type": "carousel", - "columns": [ - { - "thumbnailImageUrl": - "https://example.com/item1.jpg", - "title": "this is menu1", - "text": "description1", - "actions": [ - { - "type": "postback", - "label": "postback1", - "displayText": "postback text1", - "data": "action=buy&itemid=1" - }, - { - "type": "message", - "label": "message1", - "text": "message text1" - }, - { - "type": "uri", - "label": "uri1", - "uri": "http://example.com/1" - } - ] - }, - { - "thumbnailImageUrl": - "https://example.com/item2.jpg", - "imageBackgroundColor": "#000000", - "title": "this is menu2", - "text": "description2", - "actions": [ - { - "type": "postback", - "label": "postback2", - "displayText": "postback text2", - "data": "action=buy&itemid=2" - }, - { - "type": "message", - "label": "message2", - "text": "message text2" - }, - { - "type": "uri", - "label": "uri2", - "uri": "http://example.com/2" - } - ] - }, - { - "thumbnailImageUrl": - "https://example.com/item3.jpg", - "title": "this is menu3", - "text": "description3", - "actions": [ - { - "type": "datetimepicker", - "label": "datetime picker date", - "data": "action=sell&itemid=2&mode=date", - "mode": "date", - "initial": "2013-04-01", - "min": "2011-06-23", - "max": "2017-09-08" - }, - { - "type": "datetimepicker", - "label": "datetime picker time", - "data": "action=sell&itemid=2&mode=time", - "mode": "time", - "initial": "10:00", - "min": "00:00", - "max": "23:59" - }, - { - "type": "datetimepicker", - "label": "datetime picker datetime", - "data": "action=sell&itemid=2&mode=datetime", - "mode": "datetime", - "initial": "2013-04-01T10:00", - "min": "2011-06-23T00:00", - "max": "2017-09-08T23:59" - } - ] - } - ], - } - }] - - self.image_carousel_template_message = TemplateSendMessage( - alt_text='Image carousel template', - template=ImageCarouselTemplate( - columns=[ - ImageCarouselColumn( - image_url='https://example.com/' - 'item1.jpg', - action=PostbackAction( - label='postback1', - data='action=buy&itemid=1' - ) - ), - ImageCarouselColumn( - image_url='https://example.com' - '/item2.jpg', - action=MessageAction( - label='message2', - text='message text2' - ) - ), - ImageCarouselColumn( - image_url='https://example.com/' - 'item3.jpg', - action=URIAction( - label='uri1', - uri='https://example.com/1' - ) - ) - ] - ) - ) - - self.image_carousel_message = [{ - "type": "template", - "altText": "Image carousel template", - "template": { - "type": "image_carousel", - "columns": [ - { - "imageUrl": "https://example.com/item1.jpg", - "action": { - "type": "postback", - "label": "postback1", - "data": "action=buy&itemid=1", - } - }, - { - "imageUrl": "https://example.com/item2.jpg", - "action": { - "type": "message", - "label": "message2", - "text": "message text2" - } - }, - { - "imageUrl": "https://example.com/item3.jpg", - "action": { - "type": "uri", - "label": "uri1", - "uri": "https://example.com/1" - } - } - ] - } - }] - - @responses.activate - def test_push_buttons_template_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', self.button_template_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": self.button_message - } - ) - - @responses.activate - def test_reply_buttons_template_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', - json={}, status=200 - ) - - self.tested.reply_message('replyToken', self.button_template_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') - self.assertEqual( - json.loads(request.body), - { - "replyToken": "replyToken", - 'notificationDisabled': False, - "messages": self.button_message - } - ) - - @responses.activate - def test_push_confirm_template_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', self.confirm_template_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": self.confirm_message - } - ) - - @responses.activate - def test_reply_confirm_template_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', - json={}, status=200 - ) - - self.tested.reply_message('replyToken', self.confirm_template_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply' - ) - self.assertEqual( - json.loads(request.body), - { - "replyToken": "replyToken", - 'notificationDisabled': False, - "messages": self.confirm_message - } - ) - - @responses.activate - def test_push_carousel_template_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', self.carousel_template_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": self.carousel_message - } - ) - - @responses.activate - def test_reply_carousel_template_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', - json={}, status=200 - ) - - self.tested.reply_message('replyToken', self.carousel_template_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') - self.assertEqual( - json.loads(request.body), - { - "replyToken": "replyToken", - 'notificationDisabled': False, - "messages": self.carousel_message - } - ) - - @responses.activate - def test_multicast_carousel_template_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', - json={}, status=200 - ) - - self.tested.multicast(['to1', 'to2'], self.carousel_template_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') - self.assertEqual( - json.loads(request.body), - { - "to": ['to1', 'to2'], - 'notificationDisabled': False, - "messages": self.carousel_message - } - ) - - @responses.activate - def test_push_image_carousel_template_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', self.image_carousel_template_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": self.image_carousel_message - } - ) - - @responses.activate - def test_reply_image_carousel_template_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', - json={}, status=200 - ) - - self.tested.reply_message('replyToken', self.image_carousel_template_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') - self.assertEqual( - json.loads(request.body), - { - "replyToken": "replyToken", - 'notificationDisabled': False, - "messages": self.image_carousel_message - } - ) - - @responses.activate - def test_multicast_image_carousel_template_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', - json={}, status=200 - ) - - self.tested.multicast(['to1', 'to2'], self.image_carousel_template_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') - self.assertEqual( - json.loads(request.body), - { - "to": ['to1', 'to2'], - 'notificationDisabled': False, - "messages": self.image_carousel_message - } - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_send_text_message.py b/tests/api/test_send_text_message.py deleted file mode 100644 index 62244b147..000000000 --- a/tests/api/test_send_text_message.py +++ /dev/null @@ -1,255 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - TextSendMessage -) - - -class TestSendTestMessage(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - # test data - self.text_message = TextSendMessage(text='Hello, world') - self.message = [{"type": "text", "text": "Hello, world"}] - - @responses.activate - def test_push_text_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', self.text_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_push_text_message_with_retry_key(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200, - headers={'X-Line-Retry-Key': '123e4567-e89b-12d3-a456-426614174000'} - ) - - self.tested.push_message( - 'to', - self.text_message, - retry_key='123e4567-e89b-12d3-a456-426614174000' - ) - - request = responses.calls[0].request - - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - request.headers['X-Line-Retry-Key'], - '123e4567-e89b-12d3-a456-426614174000' - ) - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_reply_text_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', - json={}, status=200 - ) - - self.tested.reply_message('replyToken', self.text_message) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') - self.assertEqual(request.method, 'POST') - self.assertEqual( - json.loads(request.body), - { - "replyToken": "replyToken", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_multicast_text_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', - json={}, status=200 - ) - - self.tested.multicast(['to1', 'to2'], self.text_message) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') - self.assertEqual(request.method, 'POST') - self.assertEqual( - json.loads(request.body), - { - "to": ['to1', 'to2'], - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_multicast_text_message_with_retry_key(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', - json={}, status=200, - headers={'X-Line-Retry-Key': '123e4567-e89b-12d3-a456-426614174000'} - - ) - - self.tested.multicast( - ['to1', 'to2'], - self.text_message, - retry_key='123e4567-e89b-12d3-a456-426614174000' - ) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.headers['X-Line-Retry-Key'], - '123e4567-e89b-12d3-a456-426614174000' - ) - self.assertEqual( - json.loads(request.body), - { - "to": ['to1', 'to2'], - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_broadcast_text_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/broadcast', - json={}, status=200, headers={'X-Line-Request-Id': 'request_id_test'} - ) - - response = self.tested.broadcast(self.text_message) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/broadcast') - self.assertEqual(request.method, 'POST') - self.assertEqual( - json.loads(request.body), - { - 'notificationDisabled': False, - "messages": self.message - } - ) - self.assertEqual('request_id_test', response.request_id) - - # call with notification_disable=True - response = self.tested.broadcast(self.text_message, notification_disabled=True) - - request = responses.calls[1].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/broadcast') - self.assertEqual(request.method, 'POST') - self.assertEqual( - json.loads(request.body), - { - 'notificationDisabled': True, - "messages": self.message - } - ) - self.assertEqual('request_id_test', response.request_id) - - @responses.activate - def test_broadcast_text_message_with_retry_key(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/broadcast', - json={}, status=200, - headers={ - 'X-Line-Request-Id': 'request_id_test', - 'X-Line-Retry-Key': '123e4567-e89b-12d3-a456-426614174000' - } - ) - - response = self.tested.broadcast( - self.text_message, - retry_key='123e4567-e89b-12d3-a456-426614174000' - ) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/broadcast') - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.headers['X-Line-Retry-Key'], - '123e4567-e89b-12d3-a456-426614174000' - ) - self.assertEqual( - json.loads(request.body), - { - 'notificationDisabled': False, - "messages": self.message - } - ) - self.assertEqual('request_id_test', response.request_id) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_send_text_message_with_quick_reply.py b/tests/api/test_send_text_message_with_quick_reply.py deleted file mode 100644 index ae50260af..000000000 --- a/tests/api/test_send_text_message_with_quick_reply.py +++ /dev/null @@ -1,147 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - TextSendMessage, QuickReply, QuickReplyButton, - PostbackAction, MessageAction, DatetimePickerAction, - CameraAction, CameraRollAction, LocationAction -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - # test data - self.text_message = TextSendMessage(text='Hello, world') - self.message = [{"type": "text", "text": "Hello, world"}] - - @responses.activate - def test_push_text_message_with_quick_reply(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', - TextSendMessage( - text='Hello, world', - quick_reply=QuickReply(items=[ - QuickReplyButton( - image_url='https://example.com', - action=PostbackAction(label="label1", data="data1") - ), - QuickReplyButton( - action=MessageAction(label="label2", text="text2") - ), - QuickReplyButton( - action=DatetimePickerAction(label="label3", - data="data3", - mode="date") - ), - QuickReplyButton( - action=CameraAction(label="label4") - ), - QuickReplyButton( - action=CameraRollAction(label="label5") - ), - QuickReplyButton( - action=LocationAction(label="label6") - ), - ]))) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": [ - { - "type": "text", - "text": "Hello, world", - "quickReply": { - "items": [ - { - "type": "action", - "imageUrl": "https://example.com", - "action": { - "type": "postback", - "label": "label1", - "data": "data1", - } - }, - { - "type": "action", - "action": { - "type": "message", - "label": "label2", - "text": "text2", - } - }, - { - "type": "action", - "action": { - "type": "datetimepicker", - "label": "label3", - "data": "data3", - "mode": "date", - } - }, - { - "type": "action", - "action": { - "type": "camera", - "label": "label4", - } - }, - { - "type": "action", - "action": { - "type": "cameraRoll", - "label": "label5", - } - }, - { - "type": "action", - "action": { - "type": "location", - "label": "label6", - } - }, - ] - } - } - ] - } - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_send_text_message_with_sender.py b/tests/api/test_send_text_message_with_sender.py deleted file mode 100644 index f1f73eefd..000000000 --- a/tests/api/test_send_text_message_with_sender.py +++ /dev/null @@ -1,79 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - TextSendMessage, Sender -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - # test data - self.text_message = TextSendMessage(text='Hello, world') - self.message = [{"type": "text", "text": "Hello, world"}] - - @responses.activate - def test_push_text_message_with_quick_reply(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', - TextSendMessage( - text='Hello, world', - sender=Sender( - name='Cony', - icon_url='https://example.com/original.jpg' - ))) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": [ - { - "type": "text", - "text": "Hello, world", - "sender": { - "name": "Cony", - "iconUrl": "https://example.com/original.jpg" - } - } - ] - } - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_send_text_message_with_statistics_per_aggregation_unit.py b/tests/api/test_send_text_message_with_statistics_per_aggregation_unit.py deleted file mode 100644 index da5391b55..000000000 --- a/tests/api/test_send_text_message_with_statistics_per_aggregation_unit.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - TextSendMessage -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - # test data - self.text_message = TextSendMessage(text='Hello, world') - self.message = [{"type": "text", "text": "Hello, world"}] - - @responses.activate - def test_push_text_message_with_statistics_per_aggregation_unit(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', - TextSendMessage(text='Hello, world'), - custom_aggregation_units="promotion_a") - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": [ - { - "type": "text", - "text": "Hello, world" - } - ], - "customAggregationUnits": ["promotion_a"] - } - ) - - @responses.activate - def test_push_text_message_with_statistics_per_aggregation_unit_array(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', - TextSendMessage(text='Hello, world'), - custom_aggregation_units=["promotion_a"]) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": [ - { - "type": "text", - "text": "Hello, world" - } - ], - "customAggregationUnits": ["promotion_a"] - } - ) - - @responses.activate - def test_multicast_text_message_with_statistics_per_aggregation_unit(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', - json={}, status=200 - ) - - self.tested.multicast(['to'], - TextSendMessage(text='Hello, world'), - custom_aggregation_units="promotion_a") - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') - self.assertEqual( - json.loads(request.body), - { - "to": ["to"], - 'notificationDisabled': False, - "messages": [ - { - "type": "text", - "text": "Hello, world" - } - ], - "customAggregationUnits": ["promotion_a"] - } - ) - - @responses.activate - def test_multicast_text_message_with_statistics_per_aggregation_unit_array(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', - json={}, status=200 - ) - - self.tested.multicast(['to'], - TextSendMessage(text='Hello, world'), - custom_aggregation_units=["promotion_a"]) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') - self.assertEqual( - json.loads(request.body), - { - "to": ["to"], - 'notificationDisabled': False, - "messages": [ - { - "type": "text", - "text": "Hello, world" - } - ], - "customAggregationUnits": ["promotion_a"] - } - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_send_video_message.py b/tests/api/test_send_video_message.py deleted file mode 100644 index 7d5681544..000000000 --- a/tests/api/test_send_video_message.py +++ /dev/null @@ -1,121 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - VideoSendMessage -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - self.video_message = VideoSendMessage( - original_content_url='https://example.com/original.mp4', - preview_image_url='https://example.com/preview.jpg', - tracking_id='TrackId' - ) - - self.message = [{ - "type": "video", - "originalContentUrl": "https://example.com/original.mp4", - "previewImageUrl": "https://example.com/preview.jpg", - "trackingId": "TrackId" - }] - - @responses.activate - def test_push_video_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', - json={}, status=200 - ) - - self.tested.push_message('to', self.video_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') - self.assertEqual( - json.loads(request.body), - { - "to": "to", - 'notificationDisabled': False, - "messages": self.message - } - ) - - @responses.activate - def test_reply_video_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply', - json={}, status=200 - ) - - self.tested.reply_message('replyToken', self.video_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/reply') - self.assertEqual( - json.loads(request.body), - { - "replyToken": "replyToken", - "messages": self.message, - 'notificationDisabled': False, - } - ) - - @responses.activate - def test_multicast_video_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast', - json={}, status=200 - ) - - self.tested.multicast(['to1', 'to2'], self.video_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/multicast') - self.assertEqual( - json.loads(request.body), - { - "to": ['to1', 'to2'], - "messages": self.message, - "notificationDisabled": False, - } - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_set_webhook_endpoint.py b/tests/api/test_set_webhook_endpoint.py deleted file mode 100644 index 59574c6cc..000000000 --- a/tests/api/test_set_webhook_endpoint.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - @responses.activate - def test_set_webhook_endpoint(self): - responses.add( - responses.PUT, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/channel/webhook/endpoint', - json={}, - status=200 - ) - - result = self.tested.set_webhook_endpoint('endpoint') - - request = responses.calls[0].request - self.assertEqual(request.method, 'PUT') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/channel/webhook/endpoint') - self.assertEqual(result, {}) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_test_webhook_endpoint.py b/tests/api/test_test_webhook_endpoint.py deleted file mode 100644 index 6bced6c7c..000000000 --- a/tests/api/test_test_webhook_endpoint.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -import responses - -from linebot import ( - LineBotApi -) - - -class TestLineBotApi(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - - @responses.activate - def test_test_webhook_endpoint_with_endpoint(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/channel/webhook/test', - json={ - "success": True, - "timestamp": "2020-09-30T05:38:20.031Z", - "statusCode": 200, - "reason": "OK", - "detail": "200" - }, - status=200 - ) - - result = self.tested.test_webhook_endpoint('endpoint') - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/channel/webhook/test') - self.assertEqual(result.success, True) - self.assertEqual(result.timestamp, '2020-09-30T05:38:20.031Z') - self.assertEqual(result.status_code, 200) - self.assertEqual(result.reason, 'OK') - self.assertEqual(result.detail, '200') - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/api/test_validate_message_objects.py b/tests/api/test_validate_message_objects.py deleted file mode 100644 index ec933baf3..000000000 --- a/tests/api/test_validate_message_objects.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -import responses - -from linebot import ( - LineBotApi -) -from linebot.models import ( - TextSendMessage -) - - -class TestSendTestMessage(unittest.TestCase): - def setUp(self): - self.tested = LineBotApi('channel_secret') - # test data - self.text_message = TextSendMessage(text='Hello, world') - self.message = [{"type": "text", "text": "Hello, world"}] - - @responses.activate - def test_validate_push_text_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/validate/push', - json={}, status=200, headers={'X-Line-Request-Id': 'request_id_test'} - ) - - response = self.tested.validate_push_message_objects(self.text_message) - - request = responses.calls[0].request - self.assertEqual(request.method, 'POST') - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/validate/push') - self.assertEqual( - json.loads(request.body), - { - "messages": self.message - } - ) - self.assertEqual('request_id_test', response.request_id) - - @responses.activate - def test_validate_reply_text_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/validate/reply', - json={}, status=200, headers={'X-Line-Request-Id': 'request_id_test'} - ) - - response = self.tested.validate_reply_message_objects(self.text_message) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/validate/reply') - self.assertEqual(request.method, 'POST') - self.assertEqual( - json.loads(request.body), - { - "messages": self.message - } - ) - self.assertEqual('request_id_test', response.request_id) - - @responses.activate - def test_validate_multicast_text_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/validate/multicast', - json={}, status=200, headers={'X-Line-Request-Id': 'request_id_test'} - ) - - response = self.tested.validate_multicast_message_objects(self.text_message) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/validate/multicast') - self.assertEqual(request.method, 'POST') - self.assertEqual( - json.loads(request.body), - { - "messages": self.message - } - ) - self.assertEqual('request_id_test', response.request_id) - - @responses.activate - def validate_test_broadcast_text_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/validate/broadcast', - json={}, status=200, headers={'X-Line-Request-Id': 'request_id_test'} - ) - - response = self.tested.validate_broadcast_message_objects(self.text_message) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/validate/broadcast') - self.assertEqual(request.method, 'POST') - self.assertEqual( - json.loads(request.body), - { - "messages": self.message - } - ) - self.assertEqual('request_id_test', response.request_id) - - @responses.activate - def validate_test_narrowcast_text_message(self): - responses.add( - responses.POST, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/validate/narrowcast', - json={}, status=200, headers={'X-Line-Request-Id': 'request_id_test'} - ) - - response = self.tested.validate_narrowcast_message_objects(self.text_message) - - request = responses.calls[0].request - self.assertEqual( - request.url, - LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/validate/narrowcast') - self.assertEqual(request.method, 'POST') - self.assertEqual( - json.loads(request.body), - { - "messages": self.message - } - ) - self.assertEqual('request_id_test', response.request_id) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/async_api/test_async_error_handle.py b/tests/async_api/test_async_error_handle.py deleted file mode 100644 index 09a1ddc81..000000000 --- a/tests/async_api/test_async_error_handle.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -from aiohttp.test_utils import AioHTTPTestCase -from linebot.exceptions import LineBotApiError -from aiohttp import web -from linebot import AsyncLineBotApi -from linebot.aiohttp_async_http_client import AiohttpAsyncHttpClient - - -class MyAppTestCase(AioHTTPTestCase): - async def get_application(self): - self.exception = { - "message": "user id not found", - "details": [ - { - "message": "user id not found", - "property": "... some property" - } - ] - } - - async def profile(request): - return web.json_response(self.exception, status=404) - - app = web.Application() - app.router.add_get('//v2/bot/profile/failed', profile) - return app - - async def test_async_get_profile_exception(self): - self.server.skip_url_asserts = True - async_client = AiohttpAsyncHttpClient(session=self.client) - bot = AsyncLineBotApi('TOKENTOKEN', async_client, endpoint='/') - with self.assertRaises(LineBotApiError): - await bot.get_profile('failed') diff --git a/tests/async_api/test_get_message_content.py b/tests/async_api/test_get_message_content.py deleted file mode 100644 index a0a8be57e..000000000 --- a/tests/async_api/test_get_message_content.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import pytest - -from aiohttp import web - -from linebot import ( - AsyncLineBotApi -) -from linebot.aiohttp_async_http_client import AiohttpAsyncHttpClient - - -@pytest.mark.asyncio -async def test_get(aiohttp_client): - msg = ''.join('Hello, world' for i in range(1000)) - - async def hello(request): - return web.Response(text=msg) - - app = web.Application() - app.router.add_get('//v2/bot/message/abc/content', hello) - - aiohttp = await aiohttp_client(app, server_kwargs={"skip_url_asserts": True}) - async_client = AiohttpAsyncHttpClient(session=aiohttp) - - bot = AsyncLineBotApi('TOKENTOKEN', async_client, data_endpoint='/') - content = await bot.get_message_content("abc") - got = b'' - async for s in content.iter_content(): - got += s - assert got.decode('utf-8') == msg diff --git a/tests/async_api/test_get_profile.py b/tests/async_api/test_get_profile.py deleted file mode 100644 index c2a7fea7d..000000000 --- a/tests/async_api/test_get_profile.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import pytest - -from aiohttp import web - -from linebot import ( - AsyncLineBotApi -) -from linebot.aiohttp_async_http_client import AiohttpAsyncHttpClient - - -@pytest.mark.asyncio -async def test_async_profile(aiohttp_client): - expect = { - 'displayName': 'test', - 'userId': 'test', - 'language': 'en', - 'pictureUrl': 'https://obs.line-apps.com/...', - 'statusMessage': 'Hello, LINE!' - } - - async def profile(request): - return web.json_response(expect) - - app = web.Application() - app.router.add_get('//v2/bot/profile/test', profile) - - aiohttp = await aiohttp_client(app, server_kwargs={"skip_url_asserts": True}) - async_client = AiohttpAsyncHttpClient(session=aiohttp) - - bot = AsyncLineBotApi('TOKENTOKEN', async_client, endpoint='/') - profile_response = await bot.get_profile('test') - assert profile_response.user_id == expect['userId'] - assert profile_response.display_name == expect['displayName'] diff --git a/tests/models/__init__.py b/tests/models/__init__.py deleted file mode 100644 index 64a4ff91f..000000000 --- a/tests/models/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. diff --git a/tests/models/serialize_test_case.py b/tests/models/serialize_test_case.py deleted file mode 100644 index 13de0bcdc..000000000 --- a/tests/models/serialize_test_case.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import sys -import unittest -from numbers import Number - -from linebot.models import ( - Base, -) -from linebot.utils import to_camel_case - -PY3 = sys.version_info[0] == 3 - - -class SerializeTestCase(unittest.TestCase): - MESSAGE = 'message' - STICKER = 'sticker' - POSTBACK = 'postback' - CAMERA = 'camera' - CAMERA_ROLL = 'cameraRoll' - DATETIMEPICKER = 'datetimepicker' - URI = 'uri' - LOCATION = 'location' - FLEX = 'flex' - GENDER = "gender" - APP_TYPE = "appType" - AGE = "age" - AREA = "area" - SUBSCRIPTION_PERIOD = "subscriptionPeriod" - SPAN = 'span' - BUBBLE = 'bubble' - CAROUSEL = 'carousel' - BOX = 'box' - BUTTON = 'button' - FILLER = 'filler' - ICON = 'icon' - TEXT = 'text' - IMAGE = 'image' - VIDEO = 'video' - AUDIO = 'audio' - SEPARATOR = 'separator' - IMAGEMAP = 'imagemap' - ACTION = 'action' - TEMPLATE = 'template' - BUTTONS = 'buttons' - CONFIRM = 'confirm' - IMAGE_CAROUSEL = 'image_carousel' - LINEAR_GRADIENT = 'linearGradient' - - def serialize_as_dict(self, obj, type=None): - if isinstance(obj, Base): - return obj.as_json_dict() - elif isinstance(obj, dict): - ret = {to_camel_case(k): self.serialize_as_dict(v) for k, v in obj.items()} - if type is not None: - ret['type'] = type - return ret - elif isinstance(obj, list): - return [self.serialize_as_dict(elem) for elem in obj] - else: - if PY3: - self.assertIsInstance(obj, (str, bool, Number)) - else: - self.assertIsInstance(obj, (basestring, bool, Number)) # noqa - return obj - - class ConstError(TypeError): - pass - - def __setattr__(self, name, value): - if name in SerializeTestCase.__dict__: - raise self.ConstError("Can't rebind const (%s)" % name) - self.__dict__[name] = value diff --git a/tests/models/test_actions.py b/tests/models/test_actions.py deleted file mode 100644 index f5132bfef..000000000 --- a/tests/models/test_actions.py +++ /dev/null @@ -1,111 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest -from linebot.constants.postback_input_option import PostbackInputOption - -from linebot.models import ( - PostbackAction, - MessageAction, - CameraRollAction, - CameraAction, - URIAction, - LocationAction, - DatetimePickerAction, - AltUri, -) -from tests.models.serialize_test_case import SerializeTestCase - - -class TestActions(SerializeTestCase): - def test_postback(self): - arg = { - 'label': 'Buy', - 'data': 'action=buy&id=1', - 'display_text': 'buy', - 'input_option': PostbackInputOption.OPEN_KEYBOARD, - 'fill_in_text': 'fill in text', - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.POSTBACK), - PostbackAction(**arg).as_json_dict() - ) - - def test_message(self): - arg = { - 'label': 'Yes', - 'text': 'yes' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.MESSAGE), - MessageAction(**arg).as_json_dict() - ) - - def test_camera(self): - arg = { - 'label': 'camera' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.CAMERA), - CameraAction(**arg).as_json_dict() - ) - - def test_camera_roll(self): - arg = { - 'label': 'camera roll' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.CAMERA_ROLL), - CameraRollAction(**arg).as_json_dict() - ) - - def test_datetime_picker(self): - arg = { - 'label': 'Select date', - 'data': 'storeId=12345', - 'mode': 'datetime', - 'initial': '2017-12-25t00:00', - 'max': '2018-01-24t23:59', - 'min': '2017-12-25t00:00' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.DATETIMEPICKER), - DatetimePickerAction(**arg).as_json_dict() - ) - - def test_uri(self): - arg = { - 'label': 'View detail', - 'uri': 'https://example.com', - 'alt_uri': AltUri(desktop='https://example.com') - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.URI), - URIAction(**arg).as_json_dict() - ) - - def test_location(self): - arg = { - 'label': 'Location' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.LOCATION), - LocationAction(**arg).as_json_dict() - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/models/test_background.py b/tests/models/test_background.py deleted file mode 100644 index 7cc68e7ed..000000000 --- a/tests/models/test_background.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the 'License'); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -from linebot.models import LinearGradientBackground -from tests.models.serialize_test_case import SerializeTestCase - - -class TestBackground(SerializeTestCase): - def test_background(self): - arg = { - "type": "linearGradient", - "angle": "0deg", - "start_color": "#ff0000", - "end_color": "#0000ff" - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.LINEAR_GRADIENT), - LinearGradientBackground(**arg).as_json_dict() - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/models/test_base.py b/tests/models/test_base.py deleted file mode 100644 index d493fc73e..000000000 --- a/tests/models/test_base.py +++ /dev/null @@ -1,86 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import json -import unittest - -from linebot.models import Base - - -class Hoge(Base): - def __init__(self, title=None, content=None, hoge_bar=None, **kwargs): - super(Hoge, self).__init__(**kwargs) - - self.title = title - self.content = content - self.hoge_bar = hoge_bar - - -class TestBase(unittest.TestCase): - def test_as_json_string(self): - self.assertEqual( - Hoge().as_json_string(), - '{}') - self.assertEqual( - Hoge(title='title').as_json_string(), - '{"title": "title"}') - self.assertEqual( - Hoge(title='title', content='content').as_json_string(), - '{"content": "content", "title": "title"}') - self.assertEqual( - Hoge(title='title', content={"hoge": "hoge"}).as_json_string(), - '{"content": {"hoge": "hoge"}, "title": "title"}') - self.assertEqual( - Hoge(title=[1, 2]).as_json_string(), - '{"title": [1, 2]}') - self.assertEqual( - Hoge(hoge_bar='hoge_bar').as_json_string(), - '{"hogeBar": "hoge_bar"}') - - def test_as_json_dict(self): - self.assertEqual( - Hoge().as_json_dict(), - {}) - self.assertEqual( - Hoge(title='title').as_json_dict(), - {'title': 'title'}) - self.assertEqual( - Hoge(title='title', content='content').as_json_dict(), - {'content': 'content', 'title': 'title'}) - self.assertEqual( - Hoge(title='title', content={"hoge": "hoge"}).as_json_dict(), - {'content': {'hoge': 'hoge'}, 'title': 'title'}) - self.assertEqual( - Hoge(title=[1, 2]).as_json_dict(), - {'title': [1, 2]}) - - def test_new_from_json_dict(self): - self.assertEqual( - Hoge.new_from_json_dict({"title": "title"}), - Hoge(title='title')) - self.assertEqual( - Hoge.new_from_json_dict(json.loads('{"title": "title"}')), - Hoge(title='title')) - self.assertEqual( - Hoge.new_from_json_dict({"hoge_bar": "hoge_bar"}), - Hoge(hoge_bar='hoge_bar')) - self.assertEqual( - Hoge.new_from_json_dict({"hogeBar": "hoge_bar"}), - Hoge(hoge_bar='hoge_bar')) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/models/test_filter.py b/tests/models/test_filter.py deleted file mode 100644 index cd852c9e8..000000000 --- a/tests/models/test_filter.py +++ /dev/null @@ -1,79 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the 'License'); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -from linebot.models import ( - GenderFilter, - AppTypeFilter, - AreaFilter, - AgeFilter, - SubscriptionPeriodFilter -) -from tests.models.serialize_test_case import SerializeTestCase - - -class TestFilter(SerializeTestCase): - def test_gender_filter(self): - arg = { - "one_of": ["male", "female"] - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.GENDER), - GenderFilter(**arg).as_json_dict() - ) - - def test_app_type_filter(self): - arg = { - "one_of": ["ios", "android"] - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.APP_TYPE), - AppTypeFilter(**arg).as_json_dict() - ) - - def test_age_filter(self): - arg = { - "gte": "age_35", - "lt": "age_40", - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.AGE), - AgeFilter(**arg).as_json_dict() - ) - - def test_area_filter(self): - arg = { - "one_of": ["jp_34", "jp_05"] - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.AREA), - AreaFilter(**arg).as_json_dict() - ) - - def test_subscription_period_filter(self): - arg = { - "gte": "day_7", - "lt": "day_30", - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.SUBSCRIPTION_PERIOD), - SubscriptionPeriodFilter(**arg).as_json_dict() - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/models/test_flex_message.py b/tests/models/test_flex_message.py deleted file mode 100644 index 3a99c5c0c..000000000 --- a/tests/models/test_flex_message.py +++ /dev/null @@ -1,292 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the 'License'); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -from linebot.models import ( - FlexSendMessage, - BlockStyle, - BubbleStyle, - BubbleContainer, - CarouselContainer, - BoxComponent, - TextComponent, - SeparatorComponent, - ImageComponent, - ButtonComponent, - FillerComponent, - IconComponent, - SpanComponent, - VideoComponent, - URIAction, - LinearGradientBackground, -) -from tests.models.serialize_test_case import SerializeTestCase - - -class TestFlexMessage(SerializeTestCase): - def test_flex_message(self): - arg = { - 'alt_text': 'this is a flex message', - 'contents': - BubbleContainer( - body=BoxComponent( - layout='vertical', - contents=[ - TextComponent(text='hello', wrap=True, max_lines=1), - TextComponent(text='world') - ] - ) - ) - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.FLEX), - FlexSendMessage(**arg).as_json_dict() - ) - - def test_bubble_container(self): - arg = { - 'header': - BoxComponent(layout='vertical', - contents=[TextComponent(text='Header text')]), - 'body': - BoxComponent(layout='vertical', - contents=[TextComponent(text='Body text')]), - 'footer': - BoxComponent(layout='vertical', - contents=[TextComponent(text='Footer text')]), - 'styles': - BubbleStyle( - header=BlockStyle(background_color='#00ffff'), - hero=BlockStyle(background_color='#00ffff', - separator=True), - footer=BlockStyle(background_color='#00ffff', - separator=True, - separator_color='#00ffff') - ) - } - heros = [ - ImageComponent(uri='https://example.com/flex/images/image.jpg'), - BoxComponent(layout='vertical', - contents=[TextComponent(text='Body text')]), - ] - for hero in heros: - arg['hero'] = hero - self.assertEqual( - self.serialize_as_dict(arg, type=self.BUBBLE), - BubbleContainer(**arg).as_json_dict() - ) - - def test_bubble_style(self): - arg = { - 'header': - BlockStyle(background_color='#00ffff'), - 'hero': - BlockStyle(background_color='#00ffff', - separator=True), - 'footer': - BlockStyle(background_color='#00ffff', - separator=True, - separator_color='#00ffff') - } - self.assertEqual( - self.serialize_as_dict(arg), - BubbleStyle(**arg).as_json_dict() - ) - - def test_block_style(self): - arg = { - 'background_color': '#00ffff', - 'separator': True, - 'separator_color': '#000000' - } - self.assertEqual( - self.serialize_as_dict(arg), - BlockStyle(**arg).as_json_dict() - ) - - def test_carousel_container(self): - arg = { - 'contents': [ - BubbleContainer( - body=BoxComponent( - layout='vertical', - contents=[TextComponent(text='Hey')] - ) - ), - BubbleContainer( - body=BoxComponent( - layout='vertical', - contents=[TextComponent(text='Foo')] - ) - ), - ] - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.CAROUSEL), - CarouselContainer(**arg).as_json_dict() - ) - - def test_box_component(self): - arg = { - 'layout': 'vertical', - 'contents': [ - ImageComponent(url='https://example.com/flex/images/image.jpg'), - SeparatorComponent(), - TextComponent(text='Text in the box'), - ], - 'background_color': '#00000000', - 'border_width': 'light', - 'corner_radius': 'xs', - 'flex': 2 - } - - self.assertEqual( - self.serialize_as_dict(arg, type=self.BOX), - BoxComponent(**arg).as_json_dict() - ) - - def test_box_component_with_linear_gradient(self): - arg = { - 'layout': 'vertical', - 'contents': [], - 'background_color': '#00000000', - 'border_width': 'light', - 'corner_radius': 'xs', - 'flex': 2, - 'background': LinearGradientBackground( - angle='0deg', - start_color='#ff0000', - center_color='#0000ff', - end_color='#00ff00', - center_position='10%' - ) - } - - self.assertEqual( - self.serialize_as_dict(arg, type=self.BOX), - BoxComponent(**arg).as_json_dict() - ) - - def test_button_component(self): - arg = { - 'action': - URIAction(label='Tap me', - uri='https://example.com'), - 'style': 'primary', - 'color': '#0000ff' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.BUTTON), - ButtonComponent(**arg).as_json_dict() - ) - - def test_filler_component(self): - arg = { - 'flex': 2 - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.FILLER), - FillerComponent(**arg).as_json_dict() - ) - - def test_icon_component(self): - arg = { - 'url': 'https://example.com/icon/png/caution.png', - 'size': 'lg', - 'aspect_ratio': '1.91:1' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.ICON), - IconComponent(**arg).as_json_dict() - ) - - def test_image_component(self): - arg = { - 'url': 'https://example.com/flex/images/image.jpg', - 'size': 'full', - 'animated': False, - 'aspect_ratio': '1.91:1' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.IMAGE), - ImageComponent(**arg).as_json_dict() - ) - - def test_separator_component(self): - arg = { - 'color': '#000000', - 'margin': 'xxl' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.SEPARATOR), - SeparatorComponent(**arg).as_json_dict() - ) - - def test_span_component(self): - arg = { - 'type': 'span', - 'text': '蛙', - 'size': 'xxl', - 'weight': 'bold', - 'style': 'italic', - 'color': '#4f8f00', - 'decoration': 'underline' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.SPAN), - SpanComponent(**arg).as_json_dict() - ) - - def test_video_component(self): - arg = { - 'type': 'video', - 'url': 'https://example.com/video.mp4', - "preview_url": "https://example.com/video_preview.jpg", - "alt_content": { - "type": "image", - "size": "full", - "aspect_ratio": "20:13", - "aspect_mode": "cover", - "animated": False, - "url": "https://example.com/image.jpg" - }, - "aspect_ratio": "20:13" - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.VIDEO), - VideoComponent(**arg).as_json_dict() - ) - - def test_text_component(self): - arg = { - 'text': 'Hello, World!', - 'size': 'xl', - 'weight': 'bold', - 'color': '#0000ff', - 'position': 'relative', - 'offset_top': '10px', - 'decoration': 'underline', - 'max_lines': 2 - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.TEXT), - TextComponent(**arg).as_json_dict() - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/models/test_imagemap.py b/tests/models/test_imagemap.py deleted file mode 100644 index 814df0e6d..000000000 --- a/tests/models/test_imagemap.py +++ /dev/null @@ -1,126 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the 'License'); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -from linebot.models import ( - ImagemapArea, - ImagemapSendMessage, - URIImagemapAction, - MessageImagemapAction, - Video, BaseSize, ExternalLink, -) -from tests.models.serialize_test_case import SerializeTestCase - - -class TestImageMap(SerializeTestCase): - def test_image_map(self): - arg = { - 'base_url': 'https://example.com/bot/images/rm001', - 'alt_text': 'This is an imagemap', - 'base_size': BaseSize(width=1040, height=1040), - 'video': - Video( - original_content_url='https://example.com/video.mp4', - preview_image_url='https://example.com/video_preview.jpg', - area=ImagemapArea(x=0, y=0, width=1040, height=585), - external_link=ExternalLink(label='See more', - link_uri='https://example.com/see_more.html') - ), - 'actions': [ - URIImagemapAction( - link_uri='https://example.com/', - area=ImagemapArea(x=0, y=585, width=520, height=454) - ), - MessageImagemapAction( - text='Hey', - area=ImagemapArea(x=0, y=58, width=52, height=40) - ) - ] - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.IMAGEMAP), - ImagemapSendMessage(**arg).as_json_dict() - ) - - def test_video(self): - arg = { - 'original_content_url': 'https://example.com/video.mp4', - 'preview_image_url': 'https://example.com/video_preview.jpg', - 'area': ImagemapArea(x=0, y=0, width=1040, height=585), - 'external_link': ExternalLink(label='See more', - link_uri='https://example.com/see_more.html') - } - self.assertEqual( - self.serialize_as_dict(arg), - Video(**arg).as_json_dict() - ) - - def test_message_actions(self): - arg = { - 'text': 'Hey', - 'area': ImagemapArea(x=0, y=58, width=52, height=40) - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.MESSAGE), - MessageImagemapAction(**arg).as_json_dict() - ) - - def test_uri_actions(self): - arg = { - 'link_uri': 'https://example.com/', - 'area': ImagemapArea(x=0, y=585, width=520, height=454) - } - self.assertEqual( - self.serialize_as_dict(arg, self.URI), - URIImagemapAction(**arg).as_json_dict() - ) - - def test_base_size(self): - arg = { - 'width': 1040, - 'height': 1040 - } - self.assertEqual( - self.serialize_as_dict(arg), - BaseSize(**arg).as_json_dict() - ) - - def test_external_link(self): - arg = { - 'label': 'Hey link', - 'link_uri': 'https://example.com/see_more.html' - } - self.assertEqual( - self.serialize_as_dict(arg), - ExternalLink(**arg).as_json_dict() - ) - - def test_imagemap_area(self): - arg = { - 'x': 111, - 'y': 33, - 'width': 1040, - 'height': 1040 - } - self.assertEqual( - self.serialize_as_dict(arg), - ImagemapArea(**arg).as_json_dict() - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/models/test_send_messages.py b/tests/models/test_send_messages.py deleted file mode 100644 index 8d944b794..000000000 --- a/tests/models/test_send_messages.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the 'License'); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -from linebot.models import ( - TextSendMessage, - StickerSendMessage, - VideoSendMessage, - AudioSendMessage, - LocationSendMessage, - ImageSendMessage, - QuickReplyButton, - QuickReply, - CameraRollAction, - CameraAction -) -from tests.models.serialize_test_case import SerializeTestCase - - -class TestSendMessages(SerializeTestCase): - def test_text_message(self): - arg = { - 'text': 'Hello, world' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.TEXT), - TextSendMessage(**arg).as_json_dict() - ) - - def test_sticker_message(self): - arg = { - 'package_id': '1', - 'sticker_id': '1' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.STICKER), - StickerSendMessage(**arg).as_json_dict() - ) - - def test_image_message(self): - arg = { - 'original_content_url': 'https://example.com/original.jpg', - 'preview_image_url': 'https://example.com/preview.jpg' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.IMAGE), - ImageSendMessage(**arg).as_json_dict() - ) - - def test_video_message(self): - arg = { - 'type': 'video', - 'original_content_url': 'https://example.com/original.mp4', - 'preview_image_url': 'https://example.com/preview.jpg' - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.VIDEO), - VideoSendMessage(**arg).as_json_dict() - ) - - def test_video_message_wtih_track(self): - arg = { - 'type': 'video', - 'original_content_url': 'https://example.com/original.mp4', - 'preview_image_url': 'https://example.com/preview.jpg', - "tracking_id": "track_id" - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.VIDEO), - VideoSendMessage(**arg).as_json_dict() - ) - - def test_audio_message(self): - arg = { - 'original_content_url': 'https://example.com/original.m4a', - 'duration': 60000 - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.AUDIO), - AudioSendMessage(**arg).as_json_dict() - ) - - def test_location_message(self): - arg = { - 'title': 'my location', - 'address': '〒150-0002 東京都渋谷区渋谷2丁目21−1', - 'latitude': 35.65910807942215, - 'longitude': 139.70372892916203 - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.LOCATION), - LocationSendMessage(**arg).as_json_dict() - ) - - def test_quick_reply_button(self): - arg = { - 'action': CameraRollAction(label='Send photo') - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.ACTION), - QuickReplyButton(**arg).as_json_dict() - ) - - def test_quick_reply(self): - arg = { - 'items': [ - QuickReplyButton(action=CameraRollAction(label='Send photo')), - QuickReplyButton(action=CameraAction(label='Open camera')), - ] - } - self.assertEqual( - self.serialize_as_dict(arg), - QuickReply(**arg).as_json_dict() - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/models/test_template.py b/tests/models/test_template.py deleted file mode 100644 index 0e029d333..000000000 --- a/tests/models/test_template.py +++ /dev/null @@ -1,179 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the 'License'); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -from linebot.models import ( - TemplateSendMessage, - CarouselTemplate, - CarouselColumn, - ImageCarouselTemplate, - ImageCarouselColumn, - ConfirmTemplate, - ButtonsTemplate, - PostbackAction, - URIAction, - MessageAction, -) -from tests.models.serialize_test_case import SerializeTestCase - - -class TestTemplate(SerializeTestCase): - def test_template(self): - arg = { - 'type': 'template', - 'alt_text': 'This is a buttons template', - 'template': - ButtonsTemplate( - thumbnail_image_url='https=//example.com/bot/images/image.jpg', - image_aspect_ratio='rectangle', - image_size='cover', - image_background_color='#FFFFFF', - title='Menu', - text='Please select', - default_action=URIAction(label='View detail', - uri='http://example.com/page/123'), - actions=[ - PostbackAction(label='Buy', data='action=buy&itemid=155'), - URIAction(label='View detail', uri='http://example.com/page/155'), - ] - ) - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.TEMPLATE), - TemplateSendMessage(**arg).as_json_dict() - ) - - def test_button_template(self): - arg = { - 'type': 'buttons', - 'thumbnail_image_url': 'https=//example.com/bot/images/image.jpg', - 'image_aspect_ratio': 'rectangle', - 'image_size': 'cover', - 'image_background_color': '#FFFFFF', - 'title': 'Menu', - 'text': 'Please select', - 'default_action': URIAction(label='View detail', - uri='http://example.com/page/123'), - 'actions': [ - PostbackAction(label='Buy', data='action=buy&itemid=155'), - URIAction(label='View detail', uri='http://example.com/page/155'), - ] - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.BUTTONS), - ButtonsTemplate(**arg).as_json_dict() - ) - - def test_confirm_template(self): - arg = { - 'type': 'confirm', - 'text': 'Are you sure?', - 'actions': [ - MessageAction(label='Yes', text='yes...'), - MessageAction(label='No', text='no...'), - ] - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.CONFIRM), - ConfirmTemplate(**arg).as_json_dict() - ) - - def test_carousel_template(self): - arg = { - 'image_aspect_ratio': 'rectangle', - 'image_size': 'cover', - 'columns': [ - CarouselColumn( - thumbnail_image_url='https://example.com/bot/images/item1.jpg', - image_background_color='#FFFFFF', - title='this is menu', - text='description', - default_action=URIAction(label='View detail', - uri='http://example.com/page/123'), - actions=[ - PostbackAction(label='Buy', data='action=buy&itemid=155'), - URIAction(label='View detail', uri='http://example.com/page/155'), - ] - ), - CarouselColumn( - thumbnail_image_url='https://example.com/bot/images/item2.jpg', - image_background_color='#000000', - title='this is menu', - text='description', - default_action=URIAction(label='View detail', - uri='http://example.com/page/222'), - actions=[ - PostbackAction(label='Buy', data='action=buy&itemid=555'), - URIAction(label='View detail', uri='http://example.com/page/555'), - ] - ) - ] - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.CAROUSEL), - CarouselTemplate(**arg).as_json_dict() - ) - - def test_carousel_column(self): - arg = { - 'thumbnail_image_url': 'https://example.com/bot/images/item1.jpg', - 'image_background_color': '#FFFFFF', - 'title': 'this is menu', - 'text': 'description', - 'default_action': URIAction(label='View detail', - uri='http://example.com/page/123'), - 'actions': [ - PostbackAction(label='Buy', data='action=buy&itemid=155'), - URIAction(label='View detail', uri='http://example.com/page/155'), - ] - } - self.assertEqual( - self.serialize_as_dict(arg), - CarouselColumn(**arg).as_json_dict() - ) - - def test_image_carousel_template(self): - arg = { - 'columns': [ - ImageCarouselColumn( - image_url='https://example.com/bot/images/item1.jpg', - action=PostbackAction(label='Buy', data='action=buy&itemid=555') - ), - ImageCarouselColumn( - image_url='https://example.com/bot/images/item2.jpg', - action=MessageAction(label='Yes', text='yes') - ), - ] - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.IMAGE_CAROUSEL), - ImageCarouselTemplate(**arg).as_json_dict() - ) - - def test_image_carousel_column(self): - arg = { - 'image_url': 'https://example.com/bot/images/item1.jpg', - 'action': PostbackAction(label='Buy', data='action=buy&itemid=555') - } - self.assertEqual( - self.serialize_as_dict(arg), - ImageCarouselColumn(**arg).as_json_dict() - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/models/test_text_message.py b/tests/models/test_text_message.py deleted file mode 100644 index d19670c9c..000000000 --- a/tests/models/test_text_message.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the 'License'); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -from linebot.models import TextMessage -from linebot.models.emojis import Emojis -from linebot.models.mentionee import Mentionee -from linebot.models.mention import Mention -from tests.models.serialize_test_case import SerializeTestCase - - -class TestTextMessage(SerializeTestCase): - def test_emojis(self): - arg = { - "type": "text", - "text": "$ LINE emoji $", - 'emojis': [ - Emojis( - index=0, - length=6, - product_id='5ac1bfd5040ab15980c9b435', - emoji_id='001' - ), - Emojis( - index=13, - length=6, - product_id='5ac1bfd5040ab15980c9b435', - emoji_id='002' - ), - ] - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.TEXT), - TextMessage(**arg).as_json_dict() - ) - - def test_null_emojis(self): - arg = { - "type": "text", - "text": "\uDBC0\uDC84 LINE original emoji" - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.TEXT), - TextMessage(**arg).as_json_dict() - ) - - def test_mention(self): - arg = { - "type": "text", - "text": "@example Hello, world! (love)", - "mention": Mention( - mentionees=[ - Mentionee( - index=0, - length=8, - user_id="U850014438e..." - ) - ] - ), - } - self.assertEqual( - self.serialize_as_dict(arg, type=self.TEXT), - TextMessage(**arg).as_json_dict(), - ) - - def test_null_mention(self): - arg = {"type": "text", "text": "Hello, world!"} - self.assertEqual( - self.serialize_as_dict(arg, type=self.TEXT), - TextMessage(**arg).as_json_dict(), - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_aiohttp_async_http_client.py b/tests/test_aiohttp_async_http_client.py deleted file mode 100644 index e3049ad11..000000000 --- a/tests/test_aiohttp_async_http_client.py +++ /dev/null @@ -1,110 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -import pytest -from aiohttp import web - -from linebot.aiohttp_async_http_client import AiohttpAsyncHttpClient - - -@pytest.mark.asyncio -async def test_get(aiohttp_client): - async def hello(request): - return web.Response(text='Hello, world') - - app = web.Application() - app.router.add_get('/test', hello) - - client = AiohttpAsyncHttpClient(session=await aiohttp_client(app)) - resp = await client.get('/test') - assert resp.status_code == 200 - text = await resp.text - assert 'Hello, world' in text - - -@pytest.mark.asyncio -async def test_get_json(aiohttp_client): - async def hello(request): - return web.json_response({'test': 'Hello, world'}) - - app = web.Application() - app.router.add_get('/test', hello) - client = AiohttpAsyncHttpClient(session=await aiohttp_client(app)) - resp = await client.get('/test') - assert resp.status_code == 200 - json = await resp.json - assert 'Hello, world' == json['test'] - - -@pytest.mark.asyncio -async def test_get_iter(aiohttp_client): - async def hello(request): - return web.Response(text='Hello, world') - - app = web.Application() - app.router.add_get('/test', hello) - - client = AiohttpAsyncHttpClient(session=await aiohttp_client(app)) - resp = await client.get('/test') - assert resp.status_code == 200 - - buffer = '' - async for data in resp.iter_content(1024): - buffer += data.decode('utf-8') - assert 'Hello, world' in buffer - - -@pytest.mark.asyncio -async def test_post(aiohttp_client): - async def hello(request): - return web.Response(text='Hello, world') - - app = web.Application() - app.router.add_post('/test', hello) - - client = AiohttpAsyncHttpClient(session=await aiohttp_client(app)) - resp = await client.post('/test') - assert resp.status_code == 200 - text = await resp.text - assert 'Hello, world' in text - - -@pytest.mark.asyncio -async def test_delete(aiohttp_client): - async def hello(request): - return web.Response(text='Hello, world') - - app = web.Application() - app.router.add_delete('/test', hello) - - client = AiohttpAsyncHttpClient(session=await aiohttp_client(app)) - resp = await client.delete('/test') - assert resp.status_code == 200 - text = await resp.text - assert 'Hello, world' in text - - -@pytest.mark.asyncio -async def test_put(aiohttp_client): - async def hello(request): - return web.Response(text='Hello, world') - - app = web.Application() - app.router.add_put('/test', hello) - - client = AiohttpAsyncHttpClient(session=await aiohttp_client(app)) - resp = await client.put('/test') - assert resp.status_code == 200 - text = await resp.text - assert 'Hello, world' in text diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py deleted file mode 100644 index 98d5f14bf..000000000 --- a/tests/test_exceptions.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -from linebot.exceptions import LineBotApiError -from linebot.models import Error, ErrorDetail - - -class TestExceptions(unittest.TestCase): - maxDiff = None - - def test_str(self): - headers = {'X-Line-Request-Id': 'f70dd685-499a-4231-a441-f24b8d4fba21'} - line_bot_api_error = LineBotApiError( - status_code=400, - request_id='f70dd685-499a-4231-a441-f24b8d4fba21', - headers=headers, - error=Error(message='The request body has 1 error(s)', - details=[ErrorDetail(message='May not be empty', - property='messages[0].text')])) - self.assertEqual( - line_bot_api_error.__str__(), - 'LineBotApiError: status_code=400, request_id=f70dd685-499a-4231-a441-f24b8d4fba21, ' - 'error_response={"details": [{"message": "May not be empty", ' - '"property": "messages[0].text"}], "message": "The request body has 1 error(s)"}, ' - + 'headers={}'.format(headers) - ) - - def test_accepted_str(self): - headers = { - 'X-Line-Request-Id': '123e4567-e89b-12d3-a456-426655440002', - 'X-Line-Accepted-Request-Id': '123e4567-e89b-12d3-a456-426655440001' - } - line_bot_api_error = LineBotApiError( - status_code=409, - request_id='123e4567-e89b-12d3-a456-426655440002', - accepted_request_id='123e4567-e89b-12d3-a456-426655440001', - headers=headers, - error=Error(message='The retry key is already accepted') - ) - self.assertEqual( - line_bot_api_error.__str__(), - 'LineBotApiError: status_code=409, request_id=123e4567-e89b-12d3-a456-426655440002, ' - 'accepted_request_id=123e4567-e89b-12d3-a456-426655440001, ' - 'error_response={"details": [], "message": "The retry key is already accepted"}, ' - + 'headers={}'.format(headers) - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_utils.py b/tests/test_utils.py deleted file mode 100644 index 1ff3c54b7..000000000 --- a/tests/test_utils.py +++ /dev/null @@ -1,44 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import unittest - -from linebot.utils import to_camel_case, to_snake_case, safe_compare_digest - - -class TestUtils(unittest.TestCase): - def test_to_snake_case(self): - self.assertEqual(to_snake_case('hogeBarFuga'), 'hoge_bar_fuga') - self.assertEqual(to_snake_case('uniqueMediaPlayed100Percent'), 'unique_media_played_100_percent') - self.assertEqual(to_snake_case('festival20Days'), 'festival_20_days') - self.assertEqual(to_snake_case('festival20days'), 'festival_20_days') - - def test_to_camel_case(self): - self.assertEqual(to_camel_case('hoge_bar'), 'hogeBar') - self.assertEqual(to_camel_case('unique_media_played_100_percent'), 'uniqueMediaPlayed100Percent') - - def test_safe_compare_digest_true(self): - self.assertTrue(safe_compare_digest('/gg9a+LvFevTH1sd7', '/gg9a+LvFevTH1sd7')) - - def test_safe_compare_digest_false_same_size(self): - self.assertFalse(safe_compare_digest('/gg9a+LvFevTH1sd7', '/gg9a+LvFevTH1sd8')) - - def test_safe_compare_digest_false_different_size(self): - self.assertFalse(safe_compare_digest('/gg9a+LvFevTH1sd7', '/gg9a+LvFevTH1sd78')) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_webhook.py b/tests/test_webhook.py deleted file mode 100644 index 6a551fe26..000000000 --- a/tests/test_webhook.py +++ /dev/null @@ -1,722 +0,0 @@ -# -*- coding: utf-8 -*- - -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -from __future__ import unicode_literals, absolute_import - -import os -import unittest -from builtins import open -import inspect - -from linebot import ( - SignatureValidator, WebhookParser, WebhookHandler, utils -) -from linebot.models import ( - MessageEvent, FollowEvent, UnfollowEvent, JoinEvent, - LeaveEvent, PostbackEvent, BeaconEvent, AccountLinkEvent, - MemberJoinedEvent, MemberLeftEvent, - UnknownEvent, - TextMessage, ImageMessage, VideoMessage, AudioMessage, - LocationMessage, StickerMessage, FileMessage, - SourceUser, SourceRoom, SourceGroup, -) -from linebot.models.delivery_context import DeliveryContext -from linebot.models.events import UnsendEvent, VideoPlayCompleteEvent -from linebot.models.unsend import Unsend -from linebot.models.video_play_complete import VideoPlayComplete -from linebot.utils import PY3 - - -class TestSignatureValidator(unittest.TestCase): - def test_validate(self): - signature_validator = SignatureValidator('channel_secret') - - self.assertEqual( - signature_validator.validate( - 'bodybodybodybody', '/gg9a+LvFevTH1sd7XCQycD7tsWclCsInj7MhBHxN7k='), - True - ) - self.assertEqual( - signature_validator.validate( - 'bodybodybodybody', 'invalid_signature'), - False - ) - - -class TestWebhookParser(unittest.TestCase): - def setUp(self): - parser = WebhookParser('channel_secret') - # mock - parser.signature_validator.validate = lambda a, b: True - self.parser = parser - - def test_parse(self): - file_dir = os.path.dirname(__file__) - webhook_sample_json_path = os.path.join(file_dir, 'text', 'webhook.json') - with open(webhook_sample_json_path) as fp: - body = fp.read() - - events = self.parser.parse(body, 'channel_secret') - - # events count - self.assertEqual(len(events), 27) - - # MessageEvent, SourceUser, TextMessage - self.assertIsInstance(events[0], MessageEvent) - self.assertEqual(events[0].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[0].type, 'message') - self.assertEqual(events[0].mode, 'active') - self.assertEqual(events[0].timestamp, 1462629479859) - self.assertIsInstance(events[0].source, SourceUser) - self.assertEqual(events[0].source.type, 'user') - self.assertEqual(events[0].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[0].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[0].delivery_context, DeliveryContext) - self.assertFalse(events[0].delivery_context.is_redelivery) - self.assertIsInstance(events[0].message, TextMessage) - self.assertEqual(events[0].message.id, '325708') - self.assertEqual(events[0].message.type, 'text') - self.assertEqual(events[0].message.text, 'Hello, world') - - # MessageEvent, SourceRoom, ImageMessage - self.assertIsInstance(events[1], MessageEvent) - self.assertEqual(events[1].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[1].type, 'message') - self.assertEqual(events[1].mode, 'active') - self.assertEqual(events[1].timestamp, 1462629479859) - self.assertIsInstance(events[1].source, SourceRoom) - self.assertEqual(events[1].source.type, 'room') - self.assertEqual(events[1].source.room_id, 'Ra8dbf4673c4c812cd491258042226c99') - self.assertEqual(events[1].source.user_id, None) - self.assertEqual(events[1].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[1].delivery_context, DeliveryContext) - self.assertFalse(events[1].delivery_context.is_redelivery) - self.assertIsInstance(events[1].message, ImageMessage) - self.assertEqual(events[1].message.id, '325708') - self.assertEqual(events[1].message.type, 'image') - self.assertEqual(events[1].message.content_provider.type, 'external') - self.assertEqual(events[1].message.content_provider.original_content_url, - "https://example.com") - self.assertEqual(events[1].message.content_provider.preview_image_url, - "https://example.com") - - # MessageEvent, SourceUser, VideoMessage - self.assertIsInstance(events[2], MessageEvent) - self.assertEqual(events[2].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[2].type, 'message') - self.assertEqual(events[2].mode, 'active') - self.assertEqual(events[2].timestamp, 1462629479859) - self.assertIsInstance(events[2].source, SourceUser) - self.assertEqual(events[2].source.type, 'user') - self.assertEqual(events[2].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[2].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[2].delivery_context, DeliveryContext) - self.assertFalse(events[2].delivery_context.is_redelivery) - self.assertIsInstance(events[2].message, VideoMessage) - self.assertEqual(events[2].message.id, '325708') - self.assertEqual(events[2].message.type, 'video') - self.assertEqual(events[2].message.duration, 60000) - self.assertEqual(events[2].message.content_provider.type, 'external') - self.assertEqual(events[2].message.content_provider.original_content_url, - "https://example.com") - self.assertEqual(events[2].message.content_provider.preview_image_url, - "https://example.com") - - # MessageEvent, SourceUser, AudioMessage - self.assertIsInstance(events[3], MessageEvent) - self.assertEqual(events[3].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[3].type, 'message') - self.assertEqual(events[3].mode, 'active') - self.assertEqual(events[3].timestamp, 1462629479859) - self.assertIsInstance(events[3].source, SourceUser) - self.assertEqual(events[3].source.type, 'user') - self.assertEqual(events[3].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[3].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[3].delivery_context, DeliveryContext) - self.assertFalse(events[3].delivery_context.is_redelivery) - self.assertIsInstance(events[3].message, AudioMessage) - self.assertEqual(events[3].message.id, '325708') - self.assertEqual(events[3].message.type, 'audio') - self.assertEqual(events[3].message.duration, 60000) - self.assertEqual(events[3].message.content_provider.type, 'external') - self.assertEqual(events[3].message.content_provider.original_content_url, - "https://example.com") - - # MessageEvent, SourceUser, LocationMessage - self.assertIsInstance(events[4], MessageEvent) - self.assertEqual(events[4].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[4].type, 'message') - self.assertEqual(events[4].mode, 'active') - self.assertEqual(events[4].timestamp, 1462629479859) - self.assertIsInstance(events[4].source, SourceUser) - self.assertEqual(events[4].source.type, 'user') - self.assertEqual(events[4].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[4].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[4].delivery_context, DeliveryContext) - self.assertFalse(events[4].delivery_context.is_redelivery) - self.assertIsInstance(events[4].message, LocationMessage) - self.assertEqual(events[4].message.id, '325708') - self.assertEqual(events[4].message.type, 'location') - self.assertEqual(events[4].message.title, 'my location') - self.assertEqual(events[4].message.address, 'Tokyo') - self.assertEqual(events[4].message.latitude, 35.65910807942215) - self.assertEqual(events[4].message.longitude, 139.70372892916203) - - # MessageEvent, SourceUser, StickerMessage - self.assertIsInstance(events[5], MessageEvent) - self.assertEqual(events[5].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[5].type, 'message') - self.assertEqual(events[5].mode, 'active') - self.assertEqual(events[5].timestamp, 1462629479859) - self.assertIsInstance(events[5].source, SourceUser) - self.assertEqual(events[5].source.type, 'user') - self.assertEqual(events[5].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[5].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[5].delivery_context, DeliveryContext) - self.assertFalse(events[5].delivery_context.is_redelivery) - self.assertIsInstance(events[5].message, StickerMessage) - self.assertEqual(events[5].message.id, '325708') - self.assertEqual(events[5].message.type, 'sticker') - self.assertEqual(events[5].message.package_id, '1') - self.assertEqual(events[5].message.sticker_id, '1') - self.assertEqual(events[5].message.sticker_resource_type, 'STATIC') - self.assertEqual(events[5].message.keywords[0], 'Love You') - self.assertEqual(events[5].message.keywords[1], 'Love') - self.assertEqual(events[5].message.text, 'Just sticker') - - # FollowEvent, SourceUser - self.assertIsInstance(events[6], FollowEvent) - self.assertEqual(events[6].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[6].type, 'follow') - self.assertEqual(events[6].mode, 'active') - self.assertEqual(events[6].timestamp, 1462629479859) - self.assertIsInstance(events[6].source, SourceUser) - self.assertEqual(events[6].source.type, 'user') - self.assertEqual(events[6].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[6].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[6].delivery_context, DeliveryContext) - self.assertFalse(events[6].delivery_context.is_redelivery) - - # UnfollowEvent, SourceUser - self.assertIsInstance(events[7], UnfollowEvent) - self.assertEqual(events[7].type, 'unfollow') - self.assertEqual(events[7].mode, 'active') - self.assertEqual(events[7].timestamp, 1462629479859) - self.assertIsInstance(events[7].source, SourceUser) - self.assertEqual(events[7].source.type, 'user') - self.assertEqual(events[7].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[7].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[7].delivery_context, DeliveryContext) - self.assertFalse(events[7].delivery_context.is_redelivery) - - # JoinEvent, SourceGroup - self.assertIsInstance(events[8], JoinEvent) - self.assertEqual(events[8].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[8].type, 'join') - self.assertEqual(events[8].mode, 'active') - self.assertEqual(events[8].timestamp, 1462629479859) - self.assertIsInstance(events[8].source, SourceGroup) - self.assertEqual(events[8].source.type, 'group') - self.assertEqual(events[8].source.group_id, 'Ca56f94637cc4347f90a25382909b24b9') - self.assertEqual(events[8].source.user_id, None) - self.assertEqual(events[8].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[8].delivery_context, DeliveryContext) - self.assertFalse(events[8].delivery_context.is_redelivery) - - # LeaveEvent, SourceGroup - self.assertIsInstance(events[9], LeaveEvent) - self.assertEqual(events[9].type, 'leave') - self.assertEqual(events[9].mode, 'active') - self.assertEqual(events[9].timestamp, 1462629479859) - self.assertIsInstance(events[9].source, SourceGroup) - self.assertEqual(events[9].source.type, 'group') - self.assertEqual(events[9].source.group_id, 'Ca56f94637cc4347f90a25382909b24b9') - self.assertEqual(events[9].source.user_id, None) - self.assertEqual(events[9].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[9].delivery_context, DeliveryContext) - self.assertFalse(events[9].delivery_context.is_redelivery) - - # PostbackEvent, SourceUser - self.assertIsInstance(events[10], PostbackEvent) - self.assertEqual(events[10].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[10].type, 'postback') - self.assertEqual(events[10].mode, 'active') - self.assertEqual(events[10].timestamp, 1462629479859) - self.assertIsInstance(events[10].source, SourceUser) - self.assertEqual(events[10].source.type, 'user') - self.assertEqual(events[10].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[10].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[10].delivery_context, DeliveryContext) - self.assertFalse(events[10].delivery_context.is_redelivery) - self.assertEqual(events[10].postback.data, 'action=buyItem&itemId=123123&color=red') - self.assertEqual(events[10].postback.params, None) - - # BeaconEvent, SourceUser - self.assertIsInstance(events[11], BeaconEvent) - self.assertEqual(events[11].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[11].type, 'beacon') - self.assertEqual(events[11].mode, 'active') - self.assertEqual(events[11].timestamp, 1462629479859) - self.assertIsInstance(events[11].source, SourceUser) - self.assertEqual(events[11].source.type, 'user') - self.assertEqual(events[11].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[11].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[11].delivery_context, DeliveryContext) - self.assertFalse(events[11].delivery_context.is_redelivery) - self.assertEqual(events[11].beacon.hwid, 'd41d8cd98f') - self.assertEqual(events[11].beacon.type, 'enter') - self.assertEqual(events[11].beacon.dm, None) - self.assertEqual(events[11].beacon.device_message, None) - - # BeaconEvent, SourceUser (with device message) - self.assertIsInstance(events[12], BeaconEvent) - self.assertEqual(events[12].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[12].type, 'beacon') - self.assertEqual(events[12].mode, 'active') - self.assertEqual(events[12].timestamp, 1462629479859) - self.assertIsInstance(events[12].source, SourceUser) - self.assertEqual(events[12].source.type, 'user') - self.assertEqual(events[12].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[12].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[12].delivery_context, DeliveryContext) - self.assertFalse(events[12].delivery_context.is_redelivery) - self.assertEqual(events[12].beacon.hwid, 'd41d8cd98f') - self.assertEqual(events[12].beacon.type, 'enter') - self.assertEqual(events[12].beacon.dm, '1234567890abcdef') - self.assertEqual(events[12].beacon.device_message, bytearray(b'\x124Vx\x90\xab\xcd\xef')) - - # AccountEvent, SourceUser - self.assertIsInstance(events[13], AccountLinkEvent) - self.assertEqual(events[13].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[13].type, 'accountLink') - self.assertEqual(events[13].mode, 'active') - self.assertEqual(events[13].timestamp, 1462629479859) - self.assertIsInstance(events[13].source, SourceUser) - self.assertEqual(events[13].source.type, 'user') - self.assertEqual(events[13].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[13].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[13].delivery_context, DeliveryContext) - self.assertFalse(events[13].delivery_context.is_redelivery) - self.assertEqual(events[13].link.result, 'ok') - self.assertEqual(events[13].link.nonce, 'Vb771wDYtXuammLszK6h9A') - - # MessageEvent, SourceGroup with userId, TextMessage - self.assertIsInstance(events[14], MessageEvent) - self.assertEqual(events[14].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[14].type, 'message') - self.assertEqual(events[14].mode, 'active') - self.assertEqual(events[14].timestamp, 1462629479859) - self.assertIsInstance(events[14].source, SourceGroup) - self.assertEqual(events[14].source.type, 'group') - self.assertEqual(events[14].source.group_id, 'Ca56f94637cc4347f90a25382909b24b9') - self.assertEqual(events[14].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[14].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[14].delivery_context, DeliveryContext) - self.assertFalse(events[14].delivery_context.is_redelivery) - self.assertIsInstance(events[14].message, TextMessage) - self.assertEqual(events[14].message.id, '325708') - self.assertEqual(events[14].message.type, 'text') - self.assertEqual(events[14].message.text, 'Hello, world') - - # MessageEvent, SourceRoom with userId, TextMessage - self.assertIsInstance(events[15], MessageEvent) - self.assertEqual(events[15].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[15].type, 'message') - self.assertEqual(events[15].mode, 'active') - self.assertEqual(events[15].timestamp, 1462629479859) - self.assertIsInstance(events[15].source, SourceRoom) - self.assertEqual(events[15].source.type, 'room') - self.assertEqual(events[15].source.room_id, 'Ra8dbf4673c4c812cd491258042226c99') - self.assertEqual(events[15].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[15].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[15].delivery_context, DeliveryContext) - self.assertFalse(events[15].delivery_context.is_redelivery) - self.assertIsInstance(events[15].message, TextMessage) - self.assertEqual(events[15].message.id, '325708') - self.assertEqual(events[15].message.type, 'text') - self.assertEqual(events[15].message.text, 'Hello, world') - - # PostbackEvent, SourceUser, with date params - self.assertIsInstance(events[16], PostbackEvent) - self.assertEqual(events[16].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[16].type, 'postback') - self.assertEqual(events[16].mode, 'active') - self.assertEqual(events[16].timestamp, 1462629479859) - self.assertIsInstance(events[16].source, SourceUser) - self.assertEqual(events[16].source.type, 'user') - self.assertEqual(events[16].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[16].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[16].delivery_context, DeliveryContext) - self.assertFalse(events[16].delivery_context.is_redelivery) - self.assertEqual(events[16].postback.data, 'action=buyItem&itemId=123123&color=red') - self.assertEqual(events[16].postback.params['date'], '2013-04-01') - - # PostbackEvent, SourceUser, with date params - self.assertIsInstance(events[17], PostbackEvent) - self.assertEqual(events[17].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[17].type, 'postback') - self.assertEqual(events[17].mode, 'active') - self.assertEqual(events[17].timestamp, 1462629479859) - self.assertIsInstance(events[17].source, SourceUser) - self.assertEqual(events[17].source.type, 'user') - self.assertEqual(events[17].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[17].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[17].delivery_context, DeliveryContext) - self.assertFalse(events[17].delivery_context.is_redelivery) - self.assertEqual(events[17].postback.data, 'action=buyItem&itemId=123123&color=red') - self.assertEqual(events[17].postback.params['time'], '10:00') - - # PostbackEvent, SourceUser, with date params - self.assertIsInstance(events[18], PostbackEvent) - self.assertEqual(events[18].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[18].type, 'postback') - self.assertEqual(events[18].mode, 'active') - self.assertEqual(events[18].timestamp, 1462629479859) - self.assertIsInstance(events[18].source, SourceUser) - self.assertEqual(events[18].source.type, 'user') - self.assertEqual(events[18].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[18].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[18].delivery_context, DeliveryContext) - self.assertFalse(events[18].delivery_context.is_redelivery) - self.assertEqual(events[18].postback.data, 'action=buyItem&itemId=123123&color=red') - self.assertEqual(events[18].postback.params['datetime'], '2013-04-01T10:00') - - # MemberJoinedEvent - self.assertIsInstance(events[19], MemberJoinedEvent) - self.assertEqual(events[19].reply_token, '0f3779fba3b349968c5d07db31eabf65') - self.assertEqual(events[19].type, 'memberJoined') - self.assertEqual(events[19].mode, 'active') - self.assertEqual(events[19].timestamp, 1462629479859) - self.assertIsInstance(events[19].source, SourceGroup) - self.assertEqual(events[19].source.type, 'group') - self.assertEqual(events[19].source.group_id, 'C4af4980629...') - self.assertEqual(events[19].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[19].delivery_context, DeliveryContext) - self.assertFalse(events[19].delivery_context.is_redelivery) - self.assertEqual(len(events[19].joined.members), 2) - self.assertIsInstance(events[19].joined.members[0], SourceUser) - self.assertEqual(events[19].joined.members[0].user_id, 'U4af4980629...') - self.assertEqual(events[19].joined.members[1].user_id, 'U91eeaf62d9...') - - # MemberLeftEvent - self.assertIsInstance(events[20], MemberLeftEvent) - self.assertEqual(events[20].type, 'memberLeft') - self.assertEqual(events[20].mode, 'active') - self.assertEqual(events[20].timestamp, 1462629479960) - self.assertIsInstance(events[20].source, SourceGroup) - self.assertEqual(events[20].source.type, 'group') - self.assertEqual(events[20].source.group_id, 'C4af4980629...') - self.assertEqual(events[20].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[20].delivery_context, DeliveryContext) - self.assertFalse(events[20].delivery_context.is_redelivery) - self.assertEqual(len(events[20].left.members), 2) - self.assertIsInstance(events[20].left.members[0], SourceUser) - self.assertEqual(events[20].left.members[0].user_id, 'U4af4980629...') - self.assertEqual(events[20].left.members[1].user_id, 'U91eeaf62d9...') - - # MessageEvent, SourceUser, FileMessage - self.assertIsInstance(events[21], MessageEvent) - self.assertEqual(events[21].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[21].type, 'message') - self.assertEqual(events[21].mode, 'active') - self.assertEqual(events[21].timestamp, 1462629479859) - self.assertIsInstance(events[21].source, SourceUser) - self.assertEqual(events[21].source.type, 'user') - self.assertEqual(events[21].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[21].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[21].delivery_context, DeliveryContext) - self.assertFalse(events[21].delivery_context.is_redelivery) - self.assertIsInstance(events[21].message, FileMessage) - self.assertEqual(events[21].message.id, '325708') - self.assertEqual(events[21].message.type, 'file') - self.assertEqual(events[21].message.file_name, "file.txt") - self.assertEqual(events[21].message.file_size, 2138) - - # UnsendEvent - self.assertIsInstance(events[22], UnsendEvent) - self.assertEqual(events[22].type, 'unsend') - self.assertEqual(events[22].mode, 'active') - self.assertEqual(events[22].timestamp, 1547817848122) - self.assertIsInstance(events[22].source, SourceGroup) - self.assertEqual(events[22].source.type, 'group') - self.assertEqual(events[22].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[22].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[22].delivery_context, DeliveryContext) - self.assertFalse(events[22].delivery_context.is_redelivery) - self.assertIsInstance(events[22].unsend, Unsend) - self.assertEqual(events[22].unsend.message_id, '325708') - - # VideoPlayCompleteEvent - self.assertIsInstance(events[23], VideoPlayCompleteEvent) - self.assertEqual(events[23].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[23].type, 'videoPlayComplete') - self.assertEqual(events[23].mode, 'active') - self.assertEqual(events[23].timestamp, 1462629479859) - self.assertIsInstance(events[23].source, SourceUser) - self.assertEqual(events[23].source.type, 'user') - self.assertEqual(events[23].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[23].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[23].delivery_context, DeliveryContext) - self.assertFalse(events[23].delivery_context.is_redelivery) - self.assertIsInstance(events[23].video_play_complete, VideoPlayComplete) - self.assertEqual(events[23].video_play_complete.tracking_id, 'track_id') - - # MessageEvent, SourceUser, ImageMessage with ImageSet - self.assertIsInstance(events[1], MessageEvent) - self.assertEqual(events[24].reply_token, 'fbf94e269485410da6b7e3a5e33283e8') - self.assertEqual(events[24].type, 'message') - self.assertEqual(events[24].mode, 'active') - self.assertEqual(events[24].timestamp, 1627356924722) - self.assertIsInstance(events[24].source, SourceUser) - self.assertEqual(events[24].source.type, 'user') - self.assertEqual(events[24].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[24].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[24].delivery_context, DeliveryContext) - self.assertFalse(events[24].delivery_context.is_redelivery) - self.assertIsInstance(events[24].message, ImageMessage) - self.assertEqual(events[24].message.id, '354718705033693861') - self.assertEqual(events[24].message.type, 'image') - self.assertEqual(events[24].message.content_provider.type, 'line') - self.assertEqual(events[24].message.image_set.id, 'E005D41A7288F41B655') - self.assertEqual(events[24].message.image_set.index, 2) - self.assertEqual(events[24].message.image_set.total, 2) - - # MessageEvent, SourceUser, TextMessage (Redeliveried) - self.assertIsInstance(events[25], MessageEvent) - self.assertEqual(events[25].reply_token, 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA') - self.assertEqual(events[25].type, 'message') - self.assertEqual(events[25].mode, 'active') - self.assertEqual(events[25].timestamp, 1462629479859) - self.assertIsInstance(events[25].source, SourceUser) - self.assertEqual(events[25].source.type, 'user') - self.assertEqual(events[25].source.user_id, 'U206d25c2ea6bd87c17655609a1c37cb8') - self.assertEqual(events[25].webhook_event_id, 'testwebhookeventid') - self.assertIsInstance(events[25].delivery_context, DeliveryContext) - self.assertTrue(events[25].delivery_context.is_redelivery) - self.assertIsInstance(events[25].message, TextMessage) - self.assertEqual(events[25].message.id, '325708') - self.assertEqual(events[25].message.type, 'text') - self.assertEqual(events[25].message.text, 'Hello, world') - - # UnknownEvent - self.assertIsInstance(events[26], UnknownEvent) - - def test_parse_webhook_req_without_destination(self): - body = """ - { - "events": [ - { - "replyToken": "00000000000000000000000000000000", - "type": "message", - "timestamp": 1561099010135, - "source": { - "type": "user", - "userId": "Udeadbeefdeadbeefdeadbeefdeadbeef" - }, - "message": { - "id": "100001", - "type": "text", - "text": "Hello, world" - } - }, - { - "replyToken": "ffffffffffffffffffffffffffffffff", - "type": "message", - "timestamp": 1561099010135, - "source": { - "type": "user", - "userId": "Udeadbeefdeadbeefdeadbeefdeadbeef" - }, - "message": { - "id": "100002", - "type": "sticker", - "packageId": "1", - "stickerId": "1" - } - } - ] - } - """ - payload = self.parser.parse(body=body, signature='channel_secret', as_payload=True) - self.assertEqual(None, payload.destination) - - -class TestWebhookHandler(unittest.TestCase): - def setUp(self): - self.handler = WebhookHandler('channel_secret') - self.use_raw_message = True - self.retrieve_attr_name = lambda x: x if self.use_raw_message \ - else utils.to_snake_case(x) - - @self.handler.add(MessageEvent, message=TextMessage) - def message_text(event, destination): - self.assertEqual('message', event.type) - self.assertEqual('text', event.message.type) - self.assertEqual('U123', destination) - - @self.handler.add(MessageEvent, - message=(ImageMessage, VideoMessage, AudioMessage)) - def message_content(event): - self.assertEqual('message', event.type) - self.assertIn( - event.message.type, - ['image', 'video', 'audio'] - ) - - @self.handler.add(MessageEvent, message=StickerMessage) - def message_sticker(event): - self.assertEqual('message', event.type) - self.assertEqual('sticker', event.message.type) - - @self.handler.add(MessageEvent, message=FileMessage) - def message_file(event): - self.assertEqual('message', event.type) - self.assertEqual('file', event.message.type) - self.assertNotEqual(event.message[self.retrieve_attr_name("fileName")], None) - self.assertNotEqual(event.message[self.retrieve_attr_name("fileSize")], None) - - @self.handler.add(MessageEvent) - def message(event): - self.assertEqual('message', event.type) - self.assertNotIn( - event.message.type, - ['text', 'image', 'video', 'audio', 'sticker'] - ) - - @self.handler.add(FollowEvent) - def follow(event, destination): - self.assertEqual('follow', event.type) - self.assertEqual('U123', destination) - - @self.handler.add(JoinEvent) - def join(event): - self.assertEqual('join', event.type) - - @self.handler.add(PostbackEvent) - def postback(event): - self.assertEqual('postback', event.type) - - @self.handler.add(BeaconEvent) - def beacon(event): - self.assertEqual('beacon', event.type) - - @self.handler.add(AccountLinkEvent) - def account_link(event): - self.assertEqual('accountLink', event.type) - - @self.handler.default() - def default(event): - self.assertNotIn( - event.type, - ['message', 'follow', 'join', 'postback', 'beacon', 'accountLink'] - ) - - def test_handler(self): - file_dir = os.path.dirname(__file__) - webhook_sample_json_path = os.path.join(file_dir, 'text', 'webhook.json') - with open(webhook_sample_json_path) as fp: - body = fp.read() - - # mock - self.handler.parser.signature_validator.validate = lambda a, b: True - - self.handler.handle(body, 'signature', self.use_raw_message) - - -class TestInvokeWebhookHandler(unittest.TestCase): - def setUp(self): - def wrap(func): - def wrapper(*args): - if PY3: - arg_spec = inspect.getfullargspec(func) - else: - arg_spec = inspect.getargspec(func) - return func(*args[0:len(arg_spec.args)]) - - return wrapper - - def func_with_0_args(): - assert True - - def func_with_1_arg(arg): - assert arg - - def func_with_2_args(arg1, arg2): - assert arg1 and arg2 - - def func_with_1_arg_with_default(arg=False): - assert arg - - def func_with_2_args_with_default(arg1=False, arg2=False): - assert arg1 and arg2 - - def func_with_1_arg_and_1_arg_with_default(arg1, arg2=False): - assert arg1 and arg2 - - @wrap - def wrapped_func_with_0_args(): - assert True - - @wrap - def wrapped_func_with_1_arg(arg): - assert arg - - @wrap - def wrapped_func_with_2_args(arg1, arg2): - assert arg1 and arg2 - - @wrap - def wrapped_func_with_1_arg_with_default(arg=False): - assert arg - - @wrap - def wrapped_func_with_2_args_with_default(arg1=False, arg2=False): - assert arg1 and arg2 - - @wrap - def wrapped_func_with_1_arg_and_1_arg_with_default( - arg1, arg2=False): - assert arg1 and arg2 - - self.functions = [ - func_with_0_args, - func_with_1_arg, - func_with_2_args, - func_with_1_arg_with_default, - func_with_2_args_with_default, - func_with_1_arg_and_1_arg_with_default, - wrapped_func_with_0_args, - wrapped_func_with_1_arg, - wrapped_func_with_2_args, - wrapped_func_with_1_arg_with_default, - wrapped_func_with_2_args_with_default, - wrapped_func_with_1_arg_and_1_arg_with_default, - ] - - def test_invoke_func(self): - class PayloadMock(object): - def __init__(self): - self.destination = True - - event = True - payload = PayloadMock() - - for func in self.functions: - WebhookHandler._WebhookHandler__invoke_func( - func, event, payload - ) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/text/webhook.json b/tests/text/webhook.json deleted file mode 100644 index 3645eeb62..000000000 --- a/tests/text/webhook.json +++ /dev/null @@ -1,531 +0,0 @@ -{ - "destination": "U123", - "events": [ - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "message", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "message": { - "id": "325708", - "type": "text", - "text": "Hello, world" - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "message", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "room", - "roomId": "Ra8dbf4673c4c812cd491258042226c99" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "message": { - "id": "325708", - "type": "image", - "contentProvider": { - "type": "external", - "originalContentUrl": "https://example.com", - "previewImageUrl": "https://example.com" - } - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "message", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "message": { - "id": "325708", - "type": "video", - "duration": 60000, - "contentProvider": { - "type": "external", - "originalContentUrl": "https://example.com", - "previewImageUrl": "https://example.com" - } - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "message", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "message": { - "id": "325708", - "type": "audio", - "duration": 60000, - "contentProvider": { - "type": "external", - "originalContentUrl": "https://example.com" - } - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "message", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "message": { - "id": "325708", - "type": "location", - "title": "my location", - "address": "Tokyo", - "latitude": 35.65910807942215, - "longitude": 139.70372892916203 - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "message", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "message": { - "id": "325708", - "type": "sticker", - "packageId": "1", - "stickerId": "1", - "stickerResourceType": "STATIC", - "keywords": ["Love You", "Love"], - "text": "Just sticker" - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "follow", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - } - }, - { - "type": "unfollow", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "join", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "group", - "groupId": "Ca56f94637cc4347f90a25382909b24b9" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - } - }, - { - "type": "leave", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "group", - "groupId": "Ca56f94637cc4347f90a25382909b24b9" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "postback", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "postback": { - "data": "action=buyItem&itemId=123123&color=red" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "beacon", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "beacon": { - "hwid": "d41d8cd98f", - "type": "enter" - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "beacon", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "beacon": { - "hwid": "d41d8cd98f", - "type": "enter", - "dm": "1234567890abcdef" - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "accountLink", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "link": { - "result": "ok", - "nonce": "Vb771wDYtXuammLszK6h9A" - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "message", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "group", - "groupId": "Ca56f94637cc4347f90a25382909b24b9", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "message": { - "id": "325708", - "type": "text", - "text": "Hello, world" - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "message", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "room", - "roomId": "Ra8dbf4673c4c812cd491258042226c99", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "message": { - "id": "325708", - "type": "text", - "text": "Hello, world" - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "postback", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "postback": { - "data": "action=buyItem&itemId=123123&color=red", - "params": { - "date": "2013-04-01" - } - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "postback", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "postback": { - "data": "action=buyItem&itemId=123123&color=red", - "params": { - "time": "10:00" - } - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "postback", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "postback": { - "data": "action=buyItem&itemId=123123&color=red", - "params": { - "datetime": "2013-04-01T10:00" - } - } - }, - { - "replyToken": "0f3779fba3b349968c5d07db31eabf65", - "type": "memberJoined", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "group", - "groupId": "C4af4980629..." - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "joined": { - "members": [ - { - "type": "user", - "userId": "U4af4980629..." - }, - { - "type": "user", - "userId": "U91eeaf62d9..." - } - ] - } - }, - { - "type": "memberLeft", - "mode": "active", - "timestamp": 1462629479960, - "source": { - "type": "group", - "groupId": "C4af4980629..." - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "left": { - "members": [ - { - "type": "user", - "userId": "U4af4980629..." - }, - { - "type": "user", - "userId": "U91eeaf62d9..." - } - ] - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "message", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "message": { - "id": "325708", - "type": "file", - "fileName": "file.txt", - "fileSize": 2138 - } - }, - { - "type": "unsend", - "mode": "active", - "timestamp": 1547817848122, - "source": { - "type": "group", - "groupId": "Ca56f94637cc4347f90a25382909b24b9", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "unsend": { - "messageId": "325708" - } - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "videoPlayComplete", - "timestamp": 1462629479859, - "mode": "active", - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "videoPlayComplete": { - "trackingId": "track_id" - } - }, - { - "type": "message", - "message": { - "type": "image", - "id": "354718705033693861", - "contentProvider": { - "type": "line" - }, - "imageSet": { - "id": "E005D41A7288F41B655", - "index": 2, - "total": 2 - } - }, - "timestamp": 1627356924722, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": false - }, - "replyToken": "fbf94e269485410da6b7e3a5e33283e8", - "mode": "active" - }, - { - "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA", - "type": "message", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": true - }, - "message": { - "id": "325708", - "type": "text", - "text": "Hello, world" - } - }, - { - "type": "undefined", - "mode": "active", - "timestamp": 1462629479859, - "source": { - "type": "user", - "userId": "U206d25c2ea6bd87c17655609a1c37cb8" - }, - "webhookEventId": "testwebhookeventid", - "deliveryContext": { - "isRedelivery": true - }, - "undefinedField": { - "1": 1 - } - } - ] -}