• Stars
    star
    1,888
  • Rank 24,567 (Top 0.5 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created about 8 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

LINE Messaging API SDK for Python

LINE Messaging API SDK for Python

PyPI version

SDK of the LINE Messaging API for Python.

Introduction

The 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.

Documentation

See the official API documentation for more information

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

Japanese: https://developers.line.biz/ja/docs/messaging-api/overview/

Requirements

  • Python >= 3.8

Installation

$ pip install line-bot-sdk

Synopsis

Usage:

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():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        app.logger.info("Invalid signature. Please check your channel access token/channel secret.")
        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

See linebot/v3/messaging/docs . Other docs are in linebot/v3/<feature>/docs/*.md.

Webhook

WebhookParser

β€» 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, InvalidSignatureError is raised.

events = parser.parse(body, signature)

for event in events:
    do_something(event)
payload = parser.parse(body, signature, as_payload=True)

for event in payload.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 with handlers added by the decorators add and default. If the signature does NOT match, InvalidSignatureError is raised.

handler.handle(body, signature)

add(self, event, message=None)

Add a handler method by using this decorator.

@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)]
        )
    )

When the event is an instance of MessageEvent and event.message is an instance of TextMessage, this handler method is called.

@handler.add(MessageEvent)
def handle_message(event, destination):
    # do something

If 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)
def handle_follow():
    # do something

If the arity of the handler method is zero, the handler method is called with no arguments.

default(self)

Set the default handler method by using this decorator.

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

If there is no handler for an event, this default handler method is called.

WebhookPayload

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

  • WebhookPayload
    • destination
    • events: list[Event]

Webhook event object

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

Hints

Examples

aiohttp-echo

Sample echo-bot with asynchronous processings.

fastapi-echo

Sample echo-bot using FastAPI

flask-echo

Sample echo-bot using Flask

flask-kitchensink

Sample bot using Flask

rich-menu

Switching richmenu script

simple-server-echo

Sample echo-bot using wsgiref.simple_server

How to deserializes JSON to FlexMessage or RichMenu

line-bot-python-sdk provides from_json method for each model. It deserializes the JSON into the specified model. Thus, you can send a JSON designed with Flex 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]
    )
)

Help and media

FAQ: https://developers.line.biz/en/faq/

Community Q&A: https://www.line-community.me/questions

News: https://developers.line.biz/en/news/

Twitter: @LINE_DEV

Versioning

This project respects semantic versioning

See http://semver.org/

Version 3.x

LINE's SDK developer team decided to generate SDK code based on OpenAPI spec. https://github.com/line/line-openapi

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.

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.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.

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.

For SDK developers

First install for development.

$ pip install -r requirements-dev.txt

You can generate new or fixed models and APIs by this command.

$ python generate-code.py

When you update line-bot-sdk-python version, please update linebot/__about__.py and generate code again.

If you edit README.rst, you should execute the following command to check the syntax of README.

$ python -m readme_renderer README.rst

Run tests

Test by using tox. We test against the following versions.

  • 3.8
  • 3.9
  • 3.10
  • 3.11

To run all tests and to run flake8 against all versions, use:

tox

To run all tests against version 3.10, use:

$ tox -e py3.10

To run a test against version 3.10 and against a specific file, use:

$ tox -e py3.10 -- tests/test_webhook.py

License

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.

More Repositories

1

armeria

Your go-to microservice framework for any situation, from the creator of Netty et al. You can build any type of microservice leveraging your favorite technologies, including gRPC, Thrift, Kotlin, Retrofit, Reactive Streams, Spring Boot and Dropwizard.
Java
4,765
star
2

promgen

Promgen is a configuration file generator for Prometheus
JavaScript
1,047
star
3

line-bot-sdk-nodejs

LINE Messaging API SDK for Node.js
TypeScript
949
star
4

line-bot-sdk-go

LINE Messaging API SDK for Go
Go
885
star
5

line-sdk-ios-swift

Provides a modern way of implementing LINE APIs.
Swift
845
star
6

line-bot-sdk-php

LINE Messaging API SDK for PHP
PHP
704
star
7

kotlin-jdsl

Kotlin library that makes it easy to build and execute queries without generated metamodel
Kotlin
702
star
8

line-bot-sdk-java

LINE Messaging API SDK for Java
Java
605
star
9

centraldogma

Highly-available version-controlled service configuration repository based on Git, ZooKeeper and HTTP/2
Java
594
star
10

line-fido2-server

FIDO2(WebAuthn) server officially certified by FIDO Alliance and Relying Party examples.
Java
508
star
11

line-bot-sdk-ruby

LINE Messaging API SDK for Ruby
Ruby
479
star
12

stellite

Stellite project is a client library and server application that offers an easy way to develop, build, and implement client/server running primarily over the QUIC protocol developed by Google as part of the Chromium project.
C++
474
star
13

garr

Collection of high performance, thread-safe, lock-free go data structures
Go
370
star
14

line-liff-v2-starter

This is a small web application that demonstrates the basic functionality of the LINE Front-end Framework (LIFF).
JavaScript
334
star
15

decaton

High throughput asynchronous task processing on Apache Kafka
Java
325
star
16

ts-remove-unused

Remove unused code from your TypeScript project
TypeScript
264
star
17

headver

SemVer compatible version specification that has {head}.{yearweek}.{build} system.
252
star
18

abc-user-feedback

ABC User Feedback is a standalone web application that manages Voice of Customer (VoC) data. It allows you to gather and sort feedback from your customers.
TypeScript
230
star
19

apng-drawable

A lightweight and fast Animated Portable Network Graphics (APNG) image decoder for Android
Kotlin
223
star
20

flutter_line_sdk

A Flutter plugin that lets developers access LINE's native SDKs in Flutter apps with Dart.
Dart
213
star
21

rules_apple_line

LINE's Apple rules for Bazel
Starlark
207
star
22

lich

A library collection that enhances the development of Android apps.
Kotlin
191
star
23

line-login-starter

LINE Login starter application
Java
138
star
24

line-liff-starter

This is a small web application that demonstrates the basic functionality of the LINE Front-end Framework (LIFF).
JavaScript
138
star
25

armeria-examples

Armeria examples
Java
137
star
26

line-openapi

OpenAPI spec of the LINE's Public APIs
JavaScript
136
star
27

line-sdk-android

LINE SDK for Android lets you integrate LINE into your Android app to create a more engaging experience for your users.
Java
133
star
28

conflr

Post R Markdown documents to Confluence
R
130
star
29

clay

Clay is an Android library project that provides image trimming which is originally an UI component of LINE Creators Studio
Kotlin
121
star
30

line-sdk-unity

Provides a modern way of implementing LINE APIs in Unity games, for iOS and Android.
C#
118
star
31

line-simple-beacon

JavaScript
109
star
32

LibriTTS-P

LibriTTS-P: A Corpus with Speaking Style and Speaker Identity Prompts for Text-to-Speech and Style Captioning
104
star
33

jnotebook_reader

πŸƒ An awesome viewer to browse and render Jupyter Notebooks from local, Amazon S3, Google Cloud Storage or MinIO
JavaScript
103
star
34

feature-flag-android

A Gradle plugin to achieve feature flag based development for Android applications.
Kotlin
100
star
35

webpack.kr

Korean translation of webpack document
MDX
91
star
36

line-things-starter

The sample codes for LINE Things Developer Trial
C++
90
star
37

liff-playground

An example app to show the usage of LIFF's API functions
TypeScript
90
star
38

grow-loader

A webpack loader to split class methods by decorators
JavaScript
88
star
39

abc-kmm-location

Location Service Manager for Kotlin Multiplatform Mobile iOS and Android
Kotlin
85
star
40

gradle-scripts

Sensible multi-project defaults for Gradle
81
star
41

vue-pivot-table-plus

An enhanced pivot table component for Vue.js
Vue
77
star
42

abc-virtual-background-maker

A standalone React application designed for creating and downloading virtual background images enriched with customizable text elements.
TypeScript
76
star
43

line-platform-feedback

LINE Platform feedback
76
star
44

gradle-multi-project-support

A collection of Gradle plugins to maintain the multi-project or multi-application in the mono-repo.
Kotlin
75
star
45

line-bot-sdk-perl

LINE Messaging API SDK for Perl
Perl
72
star
46

create-liff-app

Start developing LIFF application with a simple CLI command.
TypeScript
63
star
47

ostracon

Ostracon, a consensus algorithm, is forked from Tendermint Core. We have added VRF to Tendermint BFT. It adds randomness to PoS Validator elections and improves security.
Go
60
star
48

conditional

A super lightweight library that helps you to compose multiple conditional expressions and make them asynchronous easily.
Java
59
star
49

open-universe

Open implementation of UNIVERSE and UNIVERSE++ diffusion-based speech enhancement models.
Python
58
star
50

abc-kmm-notifications

Remote Notification Manager for Kotlin Multiplatform Mobile iOS and Android
Kotlin
57
star
51

lbm-sdk

A framework for building blockchains based LINE Blockchain Mainnet that is forked from cosmos-sdk
Go
53
star
52

liff-inspector

The universal DevTools for LIFF (WebView) browser
TypeScript
51
star
53

centraldogma-go

Go client library for Central Dogma
Go
50
star
54

line-sdk-starter-ios

A starter app demonstrating usage of the LINE iOS SDK.
Objective-C
50
star
55

centraldogma-rs

Official Rust client for Central Dogma
Rust
46
star
56

lighthouse

A user-friendly library for reproducible video moment retrieval and highlight detection.
Python
46
star
57

zipkin-lens

An alternative UI for Zipkin (Distributed Tracing), this repo is no longer used as it's already merged into upstream, please go to https://github.com/openzipkin/zipkin/tree/master/zipkin-lens
JavaScript
45
star
58

LINE-DistilBERT-Japanese

DistilBERT model pre-trained on 131 GB of Japanese web text. The teacher model is BERT-base that built in-house at LINE.
44
star
59

Flagship4j

Feature toggle system API-Client SDK follow OpenFeature specification.
Java
43
star
60

line-api-use-case-messaging-api

LINE Messaging API demo application provided by LINE API Use Case
Python
37
star
61

line-sdk-starter-android-v2

A starter application that demonstrates how to use LINE SDK V2 for Android.
Java
35
star
62

liff-mock

LIFF Mock is a LIFF Plugin that make testing your LIFF app easy.
TypeScript
35
star
63

clova-cek-sdk-nodejs

SDK of the Clova CEK for Node.js
TypeScript
34
star
64

line-sdk-starter-android

A starter app demonstrating usage of the LINE Android SDK.
Java
33
star
65

kubectl-kustomize

Docker image with kubectl and kustomize
Dockerfile
33
star
66

aes-gcm-siv

AES-GCM-SIV (RFC 8452) implementation for C, Android and Java, with hardware acceleration support.
C
33
star
67

recruiting-resources-jp

Go
33
star
68

lfb

LINE Financial Blockchain forked from gaia(https://github.com/cosmos/gaia)
Go
32
star
69

demo-rich-menu-bot

Demo bot for using rich menus with the Messaging API
PHP
31
star
70

figma-translator-vue-plugin-sample

The sample of Figma translation plugin with Vue
Vue
31
star
71

line-things-dev-board

LINE Things development board - Sample codes and schematics
HTML
29
star
72

abc-kmm-shared-storage

A local storage management library for Kotlin Multiplatform Mobile iOS and Android
Kotlin
27
star
73

line-sdk-starter-ios-v2

A starter application that demonstrates how to use LINE SDK for iOS.
Objective-C
27
star
74

gradle-multi-project-support-sample

This is a sample of build-recipe-plugin in gradle-multi-project-support
Kotlin
27
star
75

line-api-use-case-reservation-hairsalon

Hair salon reservation demo application provided by LINE API Use Case
Python
27
star
76

line-blockchain-developers-sdk-js

Javascript library for line blockchain developers
TypeScript
25
star
77

Human-Interaction-Generation

Official implementation of ICCV 2023 Oral Paper "Role-Aware Interaction Generation from Textual Description"
Python
25
star
78

networking-sr

OpenStack Neutron plugin/drivers for Segment Routing IPv6
Python
24
star
79

blockchain-sample-link-cinema

A sample service of LINE Blockchain, demonstrating how to utilize LINE Blockchain Developers and LINE BITMAX Wallet.
Go
21
star
80

abc-kmm-analytics-tools

Analytics Tools for Kotlin Multiplatform Mobile iOS and Android
Kotlin
20
star
81

clova-cek-sdk-swift

SDK of the Clova CEK for Swift
Swift
20
star
82

clova-cek-sdk-python

SDK of the Clova CEK for Python
Python
19
star
83

Meta-AI-Video-Similarity-Challenge-3rd-Place-Solution

The 3rd Place Solution of the Meta AI Video Similarity Challenge : Descriptor Track and Matching Track.
Python
18
star
84

line-bot-sample-ms

C#
17
star
85

centraldogma-python

Python client library for Central Dogma
Python
17
star
86

line-api-use-case-reservation-Restaurant

Restaurant reservation demo application provided by LINE API Use Case
Python
16
star
87

BC-node-server-sample

BusinessConnect sample server with NodeJS
JavaScript
16
star
88

japanese-large-lm-instruction-sft

16
star
89

cosmwasm

Fast and reusable WebAssembly smart contract runtime(and library) for lbm-sdk.
Rust
15
star
90

gorocksdb

A `rocksdb` wrapper for golang applications. This is forked from https://github.com/tecbot/gorocksdb.
Go
15
star
91

line-api-use-case-table-order

Table order demo application provided by LINE API Use Case
Python
15
star
92

iavl

Merkleized IAVL+ Tree implementation in Go forked from cosmos/iavl(https://github.com/cosmos/iavl)
Go
14
star
93

blockchain-sample-mage-duel

A sample service implementing a card game using the blockchain, which can serve as a guide on tokenizing game money and items.
C#
14
star
94

clova-cek-sdk-java

SDK of the Clova CEK for Java
Java
13
star
95

wasmvm

Go bindings to the CosmWasm smart contract framework. In particular, it allows you to easily compile, initialize, and execute these contracts from Go.
Go
13
star
96

tm-db

Common database interface for various database backends for Ostracon and LBM SDK. This is forked from Tendermint tm-db(https://github.com/tendermint/tm-db)
Go
13
star
97

clova-cek-sdk-elixir

SDK of the Clova CEK for Elixir
Elixir
13
star
98

line-api-use-case-liff

LINE LIFF demo application provided by LINE API Use Case
CSS
12
star
99

line-bot-pyconkr2019

LINE Chatbot for PyCon KR 2019
Python
12
star
100

line-blockchain-developers-sdk-kt

Kotlin library for line blockchain developers
Kotlin
11
star