Package: line-bot-sdk
SDK of the LINE Messaging API for Python.IntroductionThe LINE Messaging API SDK for Python makes it easy to develop bots using LINE Messaging API, and you can create a sample bot within minutes.DocumentationSee the official API documentation for more informationEnglish:https://developers.line.biz/en/docs/messaging-api/overview/Japanese:https://developers.line.biz/ja/docs/messaging-api/overview/RequirementsPython >= 3.8Installation$ pip install line-bot-sdkSynopsisUsage:fromflaskimportFlask,request,abortfromlinebot.v3import(WebhookHandler)fromlinebot.v3.exceptionsimport(InvalidSignatureError)fromlinebot.v3.messagingimport(Configuration,ApiClient,MessagingApi,ReplyMessageRequest,TextMessage)fromlinebot.v3.webhooksimport(MessageEvent,TextMessageContent)app=Flask(__name__)configuration=Configuration(access_token='YOUR_CHANNEL_ACCESS_TOKEN')handler=WebhookHandler('YOUR_CHANNEL_SECRET')@app.route("/callback",methods=['POST'])defcallback():# get X-Line-Signature header valuesignature=request.headers['X-Line-Signature']# get request body as textbody=request.get_data(as_text=True)app.logger.info("Request body: "+body)# handle webhook bodytry:handler.handle(body,signature)exceptInvalidSignatureError:app.logger.info("Invalid signature. Please check your channel access token/channel secret.")abort(400)return'OK'@handler.add(MessageEvent,message=TextMessageContent)defhandle_message(event):withApiClient(configuration)asapi_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()APISeelinebot/v3/messaging/docs. Other docs are inlinebot/v3/<feature>/docs/*.md.WebhookWebhookParser※ You can use WebhookParser__init__(self, channel_secret)parser=linebot.v3.WebhookParser('YOUR_CHANNEL_SECRET')parse(self, body, signature, as_payload=False)Parses the webhook body, and returns a list of Event objects or a WebhookPayload object (depending on as_payload).
If the signature does NOT match,InvalidSignatureErroris raised.events=parser.parse(body,signature)foreventinevents:do_something(event)payload=parser.parse(body,signature,as_payload=True)foreventinpayload.events:do_something(payload.event,payload.destination)WebhookHandler※ You can use WebhookHandler__init__(self, channel_secret)handler=linebot.v3.WebhookHandler('YOUR_CHANNEL_SECRET')handle(self, body, signature)Handles webhooks withhandlersadded
by the decoratorsaddanddefault.
If the signature does NOT match,InvalidSignatureErroris raised.handler.handle(body,signature)add(self, event, message=None)Add ahandlermethod by using this decorator.@handler.add(MessageEvent,message=TextMessage)defhandle_message(event):line_bot_api.reply_message(ReplyMessageRequest(reply_token=event.reply_token,messages=[TextMessage(text=event.message.text)]))When the event is an instance of MessageEvent and event.message is an instance of TextMessage,
this handler method is called.@handler.add(MessageEvent)defhandle_message(event,destination):# do somethingIf the arity of the handler method is more than one,
a destination property in a webhook request is passed to it as the second argument.@handler.add(FollowEvent)defhandle_follow():# do somethingIf the arity of the handler method is zero, the handler method is called with no arguments.default(self)Set the defaulthandlermethod by using this decorator.@handler.default()defdefault(event):print(event)If there is no handler for an event, this default handler method is called.WebhookPayloadhttps://developers.line.biz/en/reference/messaging-api/#request-bodyWebhookPayloaddestinationevents: list[Event]Webhook event objecthttps://developers.line.biz/en/reference/messaging-api/#webhook-event-objectsHintsExamplesaiohttp-echoSample echo-bot with asynchronous processings.fastapi-echoSample echo-bot usingFastAPIflask-echoSample echo-bot usingFlaskflask-kitchensinkSample bot usingFlaskrich-menuSwitching richmenu scriptsimple-server-echoSample echo-bot usingwsgiref.simple_serverHow to deserializes JSON to FlexMessage or RichMenuline-bot-python-sdk providesfrom_jsonmethod for each model.
It deserializes the JSON into the specified model.
Thus, you can send a JSON designed withFlex Message Simulator.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]))How to get x-line-request-id header and error messageYou may need to store thex-line-request-idheader obtained as a response from several APIs.
In this case, please use~_with_http_infofunctions. You can get headers and status codes.
Thex-line-accepted-request-idorcontent-typeheader can also be obtained in the same way.response=line_bot_api.reply_message_with_http_info(ReplyMessageRequest(reply_token=event.reply_token,messages=[TextMessage(text='see application log')]))app.logger.info("Got response with http status code: "+str(response.status_code))app.logger.info("Got x-line-request-id: "+response.headers['x-line-request-id'])app.logger.info("Got response with http body: "+str(response.data))You can get error messages fromApiExceptionwhen you useMessagingApi. Each client defines its own exception class.fromlinebot.v3.messagingimportApiException,ErrorResponsetry:line_bot_api.reply_message_with_http_info(ReplyMessageRequest(reply_token='invalid-reply-token',messages=[TextMessage(text='see application log')]))exceptApiExceptionase:app.logger.info("Got response with http status code: "+str(e.status))app.logger.info("Got x-line-request-id: "+e.headers['x-line-request-id'])app.logger.info("Got response with http body: "+str(ErrorResponse.from_json(e.body)))When you need to getx-line-accepted-request-idheader from error response, you can get it:e.headers['x-line-accepted-request-id'].Help and mediaFAQ:https://developers.line.biz/en/faq/Community Q&A:https://www.line-community.me/questionsNews:https://developers.line.biz/en/news/Twitter: @LINE_DEVVersioningThis project respects semantic versioningSeehttp://semver.org/Version 3.xLINE’s SDK developer team decided to generate SDK code based on OpenAPI spec.https://github.com/line/line-openapiAs 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 onlylinebot.v3going forward.
To utilize the latest features, we recommend you gradually transition tolinebot.v3modules in your application, although you can still continue to use the 2.xlinebotmodules.While we won’t updatelinebotmodules anymore, users can still continue to use the version 2.xlinebotmodules.
We also welcome pull requests for the version2.xand3.xmodules.How to suppress deprecation warningsIf you keep using old line-bot-sdk library (version < 3.x) but use3.x, you’ll getLineBotSdkDeprecatedIn30: 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.If it’s noisy, you can suppress this warning as follows.importwarningsfromlinebotimportLineBotSdkDeprecatedIn30## your code here...if__name__=='__main__':warnings.filterwarnings("ignore",category=LineBotSdkDeprecatedIn30)ContributingPlease checkCONTRIBUTINGbefore making a contribution.For SDK developersFirst install for development.$ pip install -r requirements-dev.txtYou can generate new or fixed models and APIs by this command.$ python generate-code.pyWhen you update line-bot-sdk-python version, please updatelinebot/__about__.pyand generate code again.If you editREADME.rst, you should execute the following command to check the syntax of README.$ python -m readme_renderer README.rstRun testsTest by using tox. We test against the following versions.3.83.93.103.113.12To run all tests and to runflake8against all versions, use:toxTo run all tests against version 3.10, use:$ tox -e py3.10To run a test against version 3.10 and against a specific file, use:$ tox -e py3.10 -- tests/test_webhook.pyLicenseCopyright (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.