Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Messaging API endpoints for friend statistics #198

Merged
merged 2 commits into from Jul 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 36 additions & 0 deletions README.rst
Expand Up @@ -460,6 +460,42 @@ https://developers.line.biz/en/reference/messaging-api/#revoke-channel-access-to

line_bot_api.revoke_channel_token(<access_token>)

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

.. code:: python

insight = line_bot_api.get_insight_message_delivery('20191231')
print(insight.api_broadcast)

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

.. code:: python

insight = line_bot_api.get_insight_followers('20191231')
print(insight.followers)

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

.. code:: python

insight = line_bot_api.get_insight_demographic()
print(insight.genders)

※ Error handling
^^^^^^^^^^^^^^^^

Expand Down
5 changes: 5 additions & 0 deletions docs/source/linebot.models.rst
Expand Up @@ -32,6 +32,11 @@ linebot.models.imagemap module

.. automodule:: linebot.models.imagemap

linebot.models.insight module
------------------------------

.. automodule:: linebot.models.insight

linebot.models.messages module
------------------------------

Expand Down
32 changes: 32 additions & 0 deletions examples/flask-kitchensink/app.py
Expand Up @@ -14,6 +14,7 @@

from __future__ import unicode_literals

import datetime
import errno
import os
import sys
Expand Down Expand Up @@ -366,6 +367,37 @@ def handle_text_message(event):
TextSendMessage(text='link_token: ' + link_token_response.link_token)
]
)
elif text == 'insight_message_delivery':
today = datetime.date.today().strftime("%Y%m%d")
response = line_bot_api.get_insight_message_delivery(today)
if response.status == 'ready':
messages = [
TextSendMessage(text='broadcast: ' + str(response.broadcast)),
TextSendMessage(text='targeting: ' + str(response.targeting)),
]
else:
messages = [TextSendMessage(text='status: ' + response.status)]
line_bot_api.reply_message(event.reply_token, messages)
elif text == 'insight_followers':
today = datetime.date.today().strftime("%Y%m%d")
response = line_bot_api.get_insight_followers(today)
if response.status == 'ready':
messages = [
TextSendMessage(text='followers: ' + str(response.followers)),
TextSendMessage(text='targetedReaches: ' + str(response.targeted_reaches)),
TextSendMessage(text='blocks: ' + str(response.blocks)),
]
else:
messages = [TextSendMessage(text='status: ' + response.status)]
line_bot_api.reply_message(event.reply_token, messages)
elif text == 'insight_demographic':
response = line_bot_api.get_insight_demographic()
if response.available:
messages = ["{gender}: {percentage}".format(gender=it.gender, percentage=it.percentage)
for it in response.genders]
else:
messages = [TextSendMessage(text='available: false')]
line_bot_api.reply_message(event.reply_token, messages)
else:
line_bot_api.reply_message(
event.reply_token, TextSendMessage(text=event.message.text))
Expand Down
58 changes: 58 additions & 0 deletions linebot/api.py
Expand Up @@ -26,6 +26,7 @@
MessageQuotaConsumptionResponse, IssueLinkTokenResponse, IssueChannelTokenResponse,
MessageDeliveryBroadcastResponse, MessageDeliveryMulticastResponse,
MessageDeliveryPushResponse, MessageDeliveryReplyResponse,
InsightMessageDeliveryResponse, InsightFollowersResponse, InsightDemographicResponse,
)


Expand Down Expand Up @@ -875,6 +876,63 @@ def revoke_channel_token(self, access_token, timeout=None):
timeout=timeout
)

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)
"""
response = self._get(
'/v2/bot/insight/message/delivery?date={date}'.format(date=date),
timeout=timeout
)

return InsightMessageDeliveryResponse.new_from_json_dict(response.json)

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)
"""
response = self._get(
'/v2/bot/insight/followers?date={date}'.format(date=date),
timeout=timeout
)

return InsightFollowersResponse.new_from_json_dict(response.json)

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 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)
"""
response = self._get(
'/v2/bot/insight/demographic',
timeout=timeout
)

return InsightDemographicResponse.new_from_json_dict(response.json)

def _get(self, path, params=None, headers=None, stream=False, timeout=None):
url = self.endpoint + path

Expand Down
11 changes: 11 additions & 0 deletions linebot/models/__init__.py
Expand Up @@ -81,6 +81,14 @@
Video,
ExternalLink,
)
from .insight import ( # noqa
DemographicInsight,
AgeInsight,
AreaInsight,
AppTypeInsight,
GenderInsight,
SubscriptionPeriodInsight,
)
from .messages import ( # noqa
Message,
TextMessage,
Expand All @@ -105,6 +113,9 @@
Content as MessageContent, # backward compatibility,
IssueLinkTokenResponse,
IssueChannelTokenResponse,
InsightMessageDeliveryResponse,
InsightFollowersResponse,
InsightDemographicResponse,
)
from .rich_menu import ( # noqa
RichMenu,
Expand Down
111 changes: 111 additions & 0 deletions linebot/models/insight.py
@@ -0,0 +1,111 @@
# -*- 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 __future__ import unicode_literals

from abc import ABCMeta

from future.utils import with_metaclass

from .base import Base


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


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


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


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


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


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