line-bot-sdk-python

LINE Messaging API SDK for Python

2,097 スター1,048 フォーク
AIによる要約
ひとことで言うと

LINE公式のMessaging APIをPythonで簡単に扱えるようにするSDKで、チャットBotの開発を数分で始められるオープンソースのライブラリです。

こんな方におすすめ

・企業:カスタマーサポートや予約受付をLINE Bot で自動化し、問い合わせ対応コストを大幅に削減できます。 ・スタートアップ:LINE上でユーザーとの双方向コミュニケーション機能を素早く実装でき、エンゲージメント向上とユーザー獲得に活かせます。 ・個人事業主・フリーランス:自分のサービスや店舗のLINE公式アカウントにBot機能を追加し、営業時間外の自動応答や情報配信を無料で実現できます。

有料サービスとの違い

TwilioなどのメッセージングAPIサービスは複数プラットフォーム対応ですが従量課金が発生します。line-bot-sdk-pythonはLINEに特化した公式SDKとして無料で利用でき、LINE Messaging APIの全機能にアクセスできます。

LINE Messaging API SDK for Python

|PyPI version|

Python用LINE Messaging API SDKです。

はじめに

LINE Messaging API SDK for Pythonを使えば、LINE Messaging APIを利用したBotの開発が簡単に行え、数分でサンプルBotを作成できます。

ドキュメント

詳細は公式APIドキュメントをご覧ください

英語: https://developers.line.biz/en/docs/messaging-api/overview/

日本語: https://developers.line.biz/ja/docs/messaging-api/overview/

動作要件

  • Python >= 3.10

インストール

::

$ pip install line-bot-sdk

使い方

使用例:

.. code:: python

from flask import Flask, request, abort

from linebot.v3 import (
    WebhookHandler
)
from linebot.v3.exceptions import (
    InvalidSignatureError
)
from linebot.v3.messaging import (
    Configuration,
    ApiClient,
    MessagingApi,
    ReplyMessageRequest,
    TextMessage
)
from linebot.v3.webhooks import (
    MessageEvent,
    TextMessageContent
)

app = Flask(__name__)

configuration = Configuration(access_token='YOUR_CHANNEL_ACCESS_TOKEN')
handler = WebhookHandler('YOUR_CHANNEL_SECRET')


@app.route("/callback", methods=['POST'])
def callback():
    # X-Line-Signatureヘッダーの値を取得
    signature = request.headers['X-Line-Signature']

    # リクエストボディをテキストとして取得
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # Webhookボディを処理
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        app.logger.info("署名が無効です。チャネルアクセストークン/チャネルシークレットを確認してください。")
        abort(400)

    return 'OK'


@handler.add(MessageEvent, message=TextMessageContent)
def handle_message(event):
    with ApiClient(configuration) as api_client:
        line_bot_api = MessagingApi(api_client)
        line_bot_api.reply_message_with_http_info(
            ReplyMessageRequest(
                reply_token=event.reply_token,
                messages=[TextMessage(text=event.message.text)]
            )
        )

if __name__ == "__main__":
    app.run()

API

linebot/v3/messaging/docs <linebot/v3/messaging/docs/MessagingApi.md>__ をご覧ください。その他のドキュメントは linebot/v3/<feature>/docs/*.md にあります。

Webhook

WebhookParser


※ WebhookParserを使用できます

\_\_init\_\_(self, channel\_secret, skip\_signature\_verification=lambda: False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code:: python

    parser = linebot.v3.WebhookParser('YOUR_CHANNEL_SECRET')

    # または skip_signature_verification オプション付き
    parser = linebot.v3.WebhookParser(
        'YOUR_CHANNEL_SECRET',
        skip_signature_verification=lambda: False

parse(self, body, signature, as_payload=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Webhookボディをパースし、Eventオブジェクトのリストまたは WebhookPayloadオブジェクト(as_payloadの値による)を返します。
署名が一致しない場合、``InvalidSignatureError`` が発生します。

.. code:: python

    events = parser.parse(body, signature)

    for event in events:
        do_something(event)

.. code:: python

    payload = parser.parse(body, signature, as_payload=True)

    for event in payload.events:
        do_something(payload.event, payload.destination)

WebhookHandler

※ WebhookHandlerを使用できます

__init__(self, channel_secret, skip_signature_verification=lambda: False) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code:: python

handler = linebot.v3.WebhookHandler('YOUR_CHANNEL_SECRET')

# または skip_signature_verification オプション付き
handler = linebot.v3.WebhookHandler(
    'YOUR_CHANNEL_SECRET',
    skip_signature_verification=lambda: False

handle(self, body, signature) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

デコレータ add <#add-self-event-message-none>__ および default <#default-self>__ で追加された ハンドラ を使ってWebhookを処理します。 署名が一致しない場合、InvalidSignatureError が発生します。

.. code:: python

handler.handle(body, signature)

add(self, event, message=None) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

このデコレータを使って ハンドラ メソッドを追加します。

.. code:: python

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    line_bot_api.reply_message(
        ReplyMessageRequest(
            reply_token=event.reply_token,
            messages=[TextMessage(text=event.message.text)]
        )
    )

イベントがMessageEventのインスタンスであり、event.messageがTextMessageのインスタンスの場合、このハンドラメソッドが呼び出されます。

.. code:: python

@handler.add(MessageEvent)
def handle_message(event, destination):
    # 何らかの処理を行う

ハンドラメソッドの引数が2つ以上の場合、Webhookリクエストのdestinationプロパティが第2引数として渡されます。

.. code:: python

@handler.add(FollowEvent)
def handle_follow():
    # 何らかの処理を行う

ハンドラメソッドの引数が0の場合、引数なしでハンドラメソッドが呼び出されます。

default(self) ^^^^^^^^^^^^^

このデコレータを使ってデフォルトの ハンドラ メソッドを設定します。

.. code:: python

@handler.default()
def default(event):
    print(event)

イベントに対するハンドラがない場合、このデフォルトハンドラメソッドが呼び出されます。

WebhookPayload


https://developers.line.biz/en/reference/messaging-api/#request-body

- WebhookPayload
    - destination
    - events: list[`Event`]

Webhookイベントオブジェクト

https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects

ヒント

サンプル


`aiohttp-echo <examples/aiohttp-echo>`__
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

非同期処理を使用したサンプルエコーBotです。

`fastapi-echo <examples/fastapi-echo>`__
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

`FastAPI <https://fastapi.tiangolo.com/>`__ を使用したサンプルエコーBotです。


`flask-echo <examples/flask-echo>`__
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

`Flask <http://flask.pocoo.org/>`__ を使用したサンプルエコーBotです。

`flask-kitchensink <examples/flask-kitchensink>`__
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

`Flask <http://flask.pocoo.org/>`__ を使用したサンプルBotです。


`rich-menu <examples/rich-menu>`__
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

リッチメニュー切替スクリプトです。

`simple-server-echo <examples/simple-server-echo>`__
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

`wsgiref.simple\_server <https://docs.python.org/3/library/wsgiref.html>`__ を使用したサンプルエコーBotです。


JSONからFlexMessageやRichMenuへのデシリアライズ方法

line-bot-python-sdkは各モデルに from_json メソッドを提供しています。 JSONを指定されたモデルにデシリアライズします。 Flex Message Simulator <https://developers.line.biz/console/fx/>__ でデザインしたJSONを送信できます。

.. code:: python

bubble_string = """{ type:"bubble", ... }"""
message = FlexMessage(alt_text="hello", contents=FlexContainer.from_json(bubble_string))
line_bot_api.reply_message(
    ReplyMessageRequest(
        reply_token=event.reply_token,
        messages=[message]
    )
)

x-line-request-idヘッダーとエラーメッセージの取得方法


いくつかのAPIからレスポンスとして取得した ``x-line-request-id`` ヘッダーを保存する必要がある場合があります。
その場合は ``~_with_http_info`` 関数を使用してください。ヘッダーとステータスコードを取得できます。
``x-line-accepted-request-id`` や ``content-type`` ヘッダーも同様の方法で取得できます。

.. code:: python

    response = line_bot_api.reply_message_with_http_info(
        ReplyMessageRequest(
            reply_token=event.reply_token,
            messages=[TextMessage(text='see application log')]
        )
    )
    app.logger.info("HTTPステータスコード: " + str(response.status_code))
    app.logger.info("x-line-request-id: " + response.headers['x-line-request-id'])
    app.logger.info("HTTPボディ: " + str(response.data))

``MessagingApi`` を使用する場合、``ApiException`` からエラーメッセージを取得できます。各クライアントは独自の例外クラスを定義しています。

.. code:: python

    from linebot.v3.messaging import ApiException, ErrorResponse
    try:
        line_bot_api.reply_message_with_http_info(
            ReplyMessageRequest(
                reply_token='invalid-reply-token',
                messages=[TextMessage(text='see application log')]
            )
        )
    except ApiException as e:
        app.logger.info("HTTPステータスコード: " + str(e.status))
        app.logger.info("x-line-request-id: " + e.headers['x-line-request-id'])
        app.logger.info("HTTPボディ: " + str(ErrorResponse.from_json(e.body)))

エラーレスポンスから ``x-line-accepted-request-id`` ヘッダーを取得する必要がある場合: ``e.headers['x-line-accepted-request-id']``


ヘルプとメディア
----------------
FAQ: https://developers.line.biz/en/faq/

ニュース: https://developers.line.biz/en/news/

バージョニング
--------------
このプロジェクトはセマンティックバージョニングに従います

- `semver.org <https://semver.org/>`_ を参照

ただし、一般公開された機能がビジネス上の理由で廃止され、完全に使用不可能になった場合は、パッチリリースとして変更をリリースします。

バージョン 3.x
-----------
LINEのSDK開発チームはOpenAPIスペックに基づいてSDKコードを生成することを決定しました。 https://github.com/line/line-openapi

その結果、LINE Bot SDK 3.xは2.xとの互換性がありません。今後のAPI変更に非常に迅速に対応できます。

今後は ``linebot.v3`` のみをメンテナンスしていきます。
最新の機能を利用するには、アプリケーション内で徐々に ``linebot.v3`` モジュールに移行することを推奨しますが、引き続き2.xの ``linebot`` モジュールも使用できます。

``linebot`` モジュールの更新は行いませんが、ユーザーは引き続きバージョン2.xの ``linebot`` モジュールを使用できます。
バージョン ``2.x`` および ``3.x`` モジュールへのプルリクエストも歓迎しています。


非推奨警告の抑制方法
--------------------
古いline-bot-sdkライブラリ(``version < 3.x``)を使い続けつつ ``3.x`` を使用している場合、以下の警告が表示されます。

::

  LineBotSdkDeprecatedIn30: Call to deprecated method get_bot_info. (Use 'from linebot.v3.messaging import MessagingApi' and 'MessagingApi(...).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.


この警告が煩わしい場合は、以下のように抑制できます。


.. code:: python

    import warnings
    from linebot import LineBotSdkDeprecatedIn30

    ## あなたのコード
    ...

    if __name__ == '__main__':
        warnings.filterwarnings("ignore", category=LineBotSdkDeprecatedIn30)


コントリビューション
--------------------
コントリビューションの前に `CONTRIBUTING <CONTRIBUTING.md>`__ を確認してください。

.. |PyPI version| image:: https://badge.fury.io/py/line-bot-sdk.svg
   :target: https://badge.fury.io/py/line-bot-sdk

ライセンス
----------

::

    Copyright (C) 2016 LINE Corp.

    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

       http://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.